准备运行环境:
1)Portable Basemap Server(PBS)用于创建地图服务
官网网址:http://geopbs.codeplex.com/
如何创建底图服务?操作步骤如下:
如果启动的时候端口冲突的话,打开PortableBasemapServer.exe.config配置端口号。
打开PortableBasemapServer.exe【以管理员身份运行】
下载底图:(mbtiles格式的)
选择区域进行下载即可:
配置启动地图服务:点击Browse选中lanzhou.mbtiles地图文件 : Map.zip
至此,本地地图服务创建成功!
获取底图服务的方法:
复制:http://192.168.168.100:7080/PBS/rest/services/lanzhou/MapServer/WMTS到浏览器中,如果报找不到路径,那么使用http://localhost:7080/PBS/rest/services/lanzhou/MapServer/WMTS,可以出现如下图:
default028mm / nativeTileMatrixSet / GoogleMapsCompatible任选一个。
在页面引用地图服务:
为什么是{z}/{y}/{x}.png,由于学习地图是半路出家,研究了好久也没有结果,暂先搁置,有大神知道的可以指导一下,哈哈!
2)openlayer框架包
选择"Examples"菜单,然后随便选择一个例子
复制路径:https://openlayers.org/en/v3.20.1/css/ol.css
https://openlayers.org/en/v3.20.1/build/ol.js
既可以下载相应的openlayer支持包。
1、初始化地图
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>01初始化地图</title>
- <meta http-equiv="X-UA-Compatible" content="chrome=1">
- <link href="css/ol.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="js/common/ol.js"></script>
- <script type="text/javascript" src="js/common/jquery-1.11.2.min.js"></script>
- </head>
- <script>
- var map_source = "wmts"; //地图的服务类型
- var map_projection = "EPSG:3857"; //地图坐标系(3857:墨卡托, 4326:经纬度)
- //map_url此处使用的是【Portable Basemap Server】作为地图服务
- var map_url = "http://localhost:7080/PBS/rest/services/lanzhou/MapServer/WMTS/tile/1.0.0/lanzhou/default/nativeTileMatrixSet/{z}/{y}/{x}.png";
- //var map_dataLayer = "layer_tdt_sl"; //地图服务的图层
- var map_zoom = 15; //初始化地图缩放级别
- var map_minZoom = 14; //地图最小缩放级别
- var map_maxZoom = 20; //地图最大缩放级别
- var map_x = 11557761.4071486; //地图x坐标(此处以兰州地图作为中心点)
- var map_y = 4307993.90607275; //地图y坐标(此处以兰州地图作为中心点)
- $(document).ready(function() {
- var baseLayer = new ol.layer.Tile({
- opacity: 1.0,
- source: new ol.source.XYZ({
- url: map_url
- })
- });
- if(baseLayer) {
- // 初始地图对象
- var map = new ol.Map({
- layers: [baseLayer],
- loadTilesWhileAnimating: true,
- target: document.getElementById("map"),
- controls: ol.control.defaults({
- attributionOptions: ({
- collapsible: false
- })
- }),
- view: new ol.View({
- center: [map_x, map_y],
- zoom: map_zoom,
- minZoom: map_minZoom,
- maxZoom: map_maxZoom
- }),
- interactions: ol.interaction.defaults({
- doubleClickZoom: false
- })
- });
- }
- });
- </script>
- <body>
- <div id="map"></div>
- </body>
- </html>
2、标绘(画笔)
02标绘.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>02标绘</title>
- <meta http-equiv="X-UA-Compatible" content="chrome=1">
- <link href="css/common/ol.css" rel="stylesheet" type="text/css" />
- <link href="css/draw/draw.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="js/common/ol.js"></script>
- <script type="text/javascript" src="js/common/jquery-1.11.2.min.js"></script>
- <script type="text/javascript" src="js/draw/util.js" ></script>
- <script type="text/javascript" src="js/draw/baseMap.js"></script>
- <script type="text/javascript" src="js/draw/drawMap.js"></script>
- <script type="text/javascript" src="js/draw/plot.js"></script>
- </head>
- <body>
- <div id="map"></div>
- <!-- 标绘菜单开始 -->
- <button id="plotBtn" title="标绘"></button>
- <!-- 标绘菜单结束 -->
- <!-- 清空按钮 -->
- <div id="clearDIV">
- <button id="clear" class="cirButton58 pngButton print_btn" onclick="clearLayer();">
- <span class="text">清空</span>
- </button>
- </div>
- <!-- 标绘div -->
- <div id='DrawBoxDiv' class='drawBox' style='display:none;'></div>
- <div id='plotMarker'></div>
- </body>
- </html>
util.js
- /**
- * JS公共工具类
- */
- var Util = {
- randomString:function(len) {//随机生成字符串
- len = len || 32;
- var $chars = 'ABC1DEFGH2IJK3LMNOQP4RSTU5VWXYZab6cdef8ghij7kmlnopq9rest0uvwxyz';
- var maxPos = $chars.length;
- var pwd = '';
- for (i = 0; i < len; i++) {
- pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
- }
- return pwd;
- }
- }
- function Map() {
- this.elements = new Array();
- //获取Map元素个数
- this.size = function() {
- return this.elements.length;
- },
- //判断Map是否为空
- this.isEmpty = function() {
- return (this.elements.length < 1);
- },
- //删除Map所有元素
- this.clear = function() {
- this.elements = new Array();
- },
- //向Map中增加元素(key, value)
- this.put = function(_key, _value) {
- if (this.containsKey(_key) == true) {
- if (this.containsValue(_value)) {
- if (this.remove(_key) == true) {
- this.elements.push({
- key : _key,
- value : _value
- });
- }
- } else {
- this.elements.push({
- key : _key,
- value : _value
- });
- }
- } else {
- this.elements.push({
- key : _key,
- value : _value
- });
- }
- },
- //删除指定key的元素,成功返回true,失败返回false
- this.remove = function(_key) {
- var bln = false;
- try {
- for (i = 0; i < this.elements.length; i++) {
- if (this.elements[i].key == _key) {
- this.elements.splice(i, 1);
- return true;
- }
- }
- } catch (e) {
- bln = false;
- }
- return bln;
- },
- //获取指定key的元素值value,失败返回null
- this.get = function(_key) {
- try {
- for (i = 0; i < this.elements.length; i++) {
- if (this.elements[i].key == _key) {
- return this.elements[i].value;
- }
- }
- } catch (e) {
- return null;
- }
- },
- //获取指定索引的元素(使用element.key,element.value获取key和value),失败返回null
- this.element = function(_index) {
- if (_index < 0 || _index >= this.elements.length) {
- return null;
- }
- return this.elements[_index];
- },
- //判断Map中是否含有指定key的元素
- this.containsKey = function(_key) {
- var bln = false;
- try {
- for (i = 0; i < this.elements.length; i++) {
- if (this.elements[i].key == _key) {
- bln = true;
- }
- }
- } catch (e) {
- bln = false;
- }
- return bln;
- },
- //判断Map中是否含有指定value的元素
- this.containsValue = function(_value) {
- var bln = false;
- try {
- for (i = 0; i < this.elements.length; i++) {
- if (this.elements[i].value == _value) {
- bln = true;
- }
- }
- } catch (e) {
- bln = false;
- }
- return bln;
- },
- //获取Map中所有key的数组(array)
- this.keys = function() {
- var arr = new Array();
- for (i = 0; i < this.elements.length; i++) {
- arr.push(this.elements[i].key);
- }
- return arr;
- },
- //获取Map中所有value的数组(array)
- this.values = function() {
- var arr = new Array();
- for (i = 0; i < this.elements.length; i++) {
- arr.push(this.elements[i].value);
- }
- return arr;
- };
- }
baseMap.js
- /**
- * 地图的底图服务模块
- */
- var map_source = "wmts"; //地图的服务类型
- var map_projection = "EPSG:3857"; //地图坐标系(3857:墨卡托, 4326:经纬度)
- //map_url此处使用的是【Portable Basemap Server】作为地图服务
- var map_url = "http://localhost:7080/PBS/rest/services/lanzhou/MapServer/WMTS/tile/1.0.0/lanzhou/default/nativeTileMatrixSet/{z}/{y}/{x}.png";
- //var map_dataLayer = "layer_tdt_sl"; //地图服务的图层
- var map_zoom = 15; //初始化地图缩放级别
- var map_minZoom = 14; //地图最小缩放级别
- var map_maxZoom = 20; //地图最大缩放级别
- var map_x = 11557761.4071486; //地图x坐标(此处以兰州地图作为中心点)
- var map_y = 4307993.90607275; //地图y坐标(此处以兰州地图作为中心点)
- $(document).ready(function() {
- var baseLayer = new ol.layer.Tile({
- opacity: 1.0,
- source: new ol.source.XYZ({
- url: map_url
- })
- });
- if(baseLayer) {
- var config = {
- center: [map_x, map_y],
- zoom: map_zoom,
- maxZoom: map_maxZoom,
- minZoom: map_minZoom
- };
- //实例化标绘地图
- DRAWMAP.init(baseLayer, config);
- }
- //标绘
- $("#plotBtn").click(function(){
- PLOT.showHideDrawBox();
- });
- });
- /**
- * 清除全部图层
- */
- function clearLayer(){
- if(confirm("要清除所有图层吗?")){
- //清空标绘图层
- for(var i = 0;i < PLOT.plotImgMap.size();i++){
- var id = PLOT.plotImgMap.elements[i].key;
- var layer = PLOT.plotImgMap.get(id);
- var source = layer.getSource();
- source.clear();
- }
- PLOT.plotImgMap.clear();//清空标绘数组
- $("#plotMarker").hide();//隐藏按钮
- }
- }
drawMap.js
- /**
- * 标绘模块的地图(实例化)
- */
- var DRAWMAP = {
- map : null, // 地图对象
- draw : null,
- vectorSource : new ol.source.Vector({
- wrapX : false
- }),
- vectorLayer : null,
- init : function(_layer, _config) {
- DRAWMAP.vectorLayer = new ol.layer.Vector({
- source : DRAWMAP.vectorSource,
- zIndex : 1000
- });
- // 初始地图对象
- DRAWMAP.map = new ol.Map({
- layers : [ _layer ],
- loadTilesWhileAnimating : true,
- target : document.getElementById("map"),
- controls : ol.control.defaults({
- attributionOptions : ({
- collapsible : false
- })
- }),
- view : new ol.View({
- center : _config.center,
- zoom : _config.zoom,
- maxZoom : _config.maxZoom,
- minZoom : _config.minZoom,
- }),
- interactions : ol.interaction.defaults({
- doubleClickZoom : false
- })
- });
- DRAWMAP.map.addLayer(DRAWMAP.vectorLayer);
- }
- };
plot.js
- /**
- * 标绘功能的事件处理模块
- */
- var PLOT = {
- plotImgMap:new Map(),//存放标绘在地图上的图片
- draw:null,
- source: new ol.source.Vector(),
- plotPic:null,
- gBHPicGroup:"",//标绘图标组名
- gCurDrawPicture:"",//图标路径
- showHideDrawBox:function(){//显示隐藏标绘界面
- $("#DrawBoxDiv").html("");
- PLOT.createDrawBox("","");
- if($("#DrawBoxDiv").css("display")!="none"){
- $("#DrawBoxDiv").css("display","none");
- $("#SaveDrawDiv").css("display","none");
- }else{
- $("#DrawBoxDiv").css("display","block");
- $("#SaveDrawDiv").css("display","block");
- }
- },
- createDrawBoxHTML:function(){
- var ix='<table class="title" >';
- ix+='<tr><td valign="center">';
- ix+='<strong> 基础绘图工具</strong>';
- ix+='</td><td align="right">';
- ix+='<img class="close" src="images/button/close.gif" title="关闭" onclick="$(\'#DrawBoxDiv\').css(\'display\',\'none\');"></img> </td></tr>';
- ix+='</table>';
- ix+='<table class="content" border="0" cellSpacing="0" cellPadding="0">';
- ix+='<tr><td><div id="drawBrushDiv" class="drawBrush">';
- ix+='<table><tr><td style="height:30px;"></td></tr>';
- ix+='<tr><td><img id="bhObj_0" src="images/tool/RedMark.png" title="标点" class="drawPicStyle3"/></td></tr>';
- ix+='<tr><td><img id="bhObj_1" src="images/tool/FGreen.png" title="小旗帜" class="drawPicStyle3"/></td></tr>';
- ix+='<tr><td><img id="bhObj_2" src="images/tool/circle.gif" title="画圆形" class="drawPicStyle3"/></td></tr>';
- ix+='<tr><td><img id="bhObj_3" src="images/tool/polyline.gif" title="画折线" class="drawPicStyle3"/></td></tr>';
- ix+='</table></div></td>';
- ix+='<td><div class="selBH"> 选择图标组: '+
- '<select id="selBHGroup" class="DefineTopicTextCtl" onchange="PLOT.showSelGroupPic()"></select></div>' +
- '<div id="drawPicDiv" class="drawPic"></div>' +
- '</td>';
- ix+='<tr></table>';
- return ix;
- },
- createDrawBox:function(){//创建标绘内容
- var html = PLOT.createDrawBoxHTML();
- $("#DrawBoxDiv").append(html);
- var OptionResults = "<option value='01常用'>01常用</option>";
- var FileNames = "<span title='A100箭头1' class='drawPicStyle' id='bht_0'><img picWidth='39' picHeight='29' src='images/plot/A100箭头1.gif' class='drawPicStyle2'></img><br>箭头1</span>";
- FileNames += "<span title='A106矩形' class='drawPicStyle' id='bht_1'><img picWidth='156' picHeight='156' src='images/plot/A106矩形.png' class='drawPicStyle2'></img><br>矩形</span>";
- FileNames += "<span title='A108圆形' class='drawPicStyle' id='bht_2'><img picWidth='156' picHeight='156' src='images/plot/A108圆形.png' class='drawPicStyle2'></img><br>圆形</span>";
- $("#selBHGroup").append(OptionResults);
- $("#drawPicDiv").append(FileNames);
- //图标组的鼠标点击事件
- $(".drawPicStyle").mousedown(function(event){
- $(".drawPicStyle").removeClass("drawPicSelected");
- $(this).addClass("drawPicSelected");
- gBHisDeleteObj=false;
- var $spanId = $(this).attr("id");
- var picObj = $("#"+$spanId+" img")[0];
- PLOT.addPlot(PLOT.getImgInfo(picObj));
- });
- //画笔图标的悬浮事件样式控制
- $(".drawPicStyle3").hover(function(){
- $(this).addClass("drawPicOver");
- },function(){
- $(this).removeClass("drawPicOver");
- });
- //画笔图标的鼠标点击事件
- $(".drawPicStyle3").mousedown(function(event){
- $(".drawPicStyle3").removeClass("drawPicSelected");
- $(this).addClass("drawPicSelected");
- switch($(this).attr("id")){
- case "bhObj_0"://标一个点图标
- PLOT.addPlot(PLOT.getImgInfo(this));
- break;
- case "bhObj_1"://标一个小旗帜
- PLOT.addPlot(PLOT.getImgInfo(this));
- break;
- case "bhObj_2"://画圆形
- PLOT.drawPlot(2);
- break;
- case "bhObj_3"://画折线
- PLOT.drawPlot(3);
- break;
- default:
- break;
- }
- });
- },
- addPlot:function(imgurl){//标绘操作
- PLOT.plotPic = imgurl;
- DRAWMAP.map.on("singleclick",function(event){
- if(PLOT.plotPic){
- var coordinate = event.coordinate;//获取当前鼠标移动后的坐标信息
- PLOT.addIcon(PLOT.plotPic,coordinate);//在地图中加入图片
- PLOT.plotPic = null;
- }
- });
- },
- getImgInfo:function(picObj){//获取图片信息(宽高、路径)
- var src = $(picObj).attr("src");
- var width="80",height="80";
- var imgObj = new Image();
- imgObj.src = src;
- if(imgObj.width != 0 && imgObj.height != 0){
- width = imgObj.width;
- height = imgObj.height;
- }
- return [width,height,src];
- },
- addIcon:function(imgurl,lonLat){//在地图中加入图片
- var lng = parseFloat(lonLat[0]);
- var lat = parseFloat(lonLat[1]);
- var point = new ol.geom.Point([lng, lat]);//转换点坐标对象
- var featureId = Util.randomString(10);
- var feature= new ol.Feature({
- geometry: point,
- labelPoint: point,
- name: "plot"
- });
- feature.setId(featureId);
- var featureSource = new ol.source.Vector();
- featureSource.addFeature(feature);
- var style = new ol.style.Style({
- fill: new ol.style.Fill({
- color: 'rgba(255, 255, 255, 0.2)'
- }),
- stroke: new ol.style.Stroke({
- color: '#ffcc33',
- width: 2
- }),
- image:new ol.style.Icon({
- offset: [0, 0],
- opacity: 1.0,
- rotateWithView: true,
- rotation: 0.0,
- scale: 1.0,
- size: [imgurl[0], imgurl[1]],
- src: imgurl[2]
- })
- });
- var getLayer= new ol.layer.Vector({
- source: featureSource,
- style: style
- });
- if(DRAWMAP.map){
- DRAWMAP.map.addLayer(getLayer);
- PLOT.plotImgMap.put(featureId,getLayer);
- }
- },
- drawPlot:function(flag){//画笔操作,比如画圆、画矩形
- if(PLOT.draw){
- DRAWMAP.map.removeInteraction(PLOT.draw);
- PLOT.draw = null;
- }
- var value = "";
- switch(parseInt(flag)){
- case 2://画圆形
- value = "Circle";
- break;
- case 3://画折线
- value = "LineString";
- break;
- }
- var sourceId = Util.randomString(10);
- PLOT.source.set("id",sourceId);
- PLOT.source.set("name","plot");
- PLOT.draw = new ol.interaction.Draw({
- source: PLOT.source,
- type:(value),
- geometryFunction: null,
- maxPoints: null
- });
- if(DRAWMAP.map){
- DRAWMAP.map.addInteraction(PLOT.draw);
- PLOT.plotImgMap.put(sourceId,PLOT.plotLayer());
- }
- //画笔绘图结束
- PLOT.draw.on("drawend", function(evt) {
- DRAWMAP.map.removeInteraction(PLOT.draw);
- DRAWMAP.map.addLayer(PLOT.plotLayer());//添加动态画图的图层
- }, this);
- },
- plotLayer: function(){//返回layer图层
- return new ol.layer.Vector({
- source: PLOT.source,
- style: new ol.style.Style({
- fill: new ol.style.Fill({
- color: 'rgba(255, 255, 255, 0.2)'
- }),
- stroke: new ol.style.Stroke({
- color: '#ffcc33',
- width: 2
- }),
- image: new ol.style.Circle({
- radius: 7,
- fill: new ol.style.Fill({
- color: '#ffcc33'
- })
- })
- })
- });
- }
- }
3、增加图层和弹出框
03增加图层和弹出框.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>03增加图层和弹出框</title>
- <meta http-equiv="X-UA-Compatible" content="chrome=1">
- <link href="css/common/ol.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="js/common/ol.js"></script>
- <script type="text/javascript" src="js/common/jquery-1.11.2.min.js"></script>
- <script type="text/javascript" src="js/03增加图层和弹出框/MYMap.js"></script>
- </head>
- <style>
- .ol-popup {
- position: absolute;
- background-color: white;
- padding-top: 5px;
- padding-left: 10px;
- padding-right: 10px;
- padding-bottom: 10px;
- border-radius: 2px;
- border: 1px solid #cccccc;
- bottom: 12px;
- left: -50px;
- }
- .ol-popup:after,
- .ol-popup:before {
- top: 100%;
- border: solid transparent;
- content: " ";
- position: absolute;
- }
- /*border-top-color:用于制作三角形*/
- .ol-popup:after {
- border-top-color: white;
- border-width: 10px;
- left: 48px;
- margin-left: -10px;
- }
- .ol-popup:before {
- border-top-color: #cccccc;
- border-width: 11px;
- left: 48px;
- margin-left: -11px;
- }
- .ol-popup-title {
- border-bottom: 1px solid #cccccc;
- padding-bottom: 3px;
- }
- .ol-popup-content {
- margin-top: 8px;
- width:260px;
- }
- .ol-popup-closer {
- text-decoration: none;
- position: absolute;
- top: 5px;
- right: 10px;
- }
- .ol-popup-closer:after {
- content: "✖";
- }
- #moveTaxi{
- position: absolute;
- top: 5%;
- left: 5%;
- background-color: rgba(0, 60, 136, .5);
- color: white;
- }
- #moveTaxi:hover{
- cursor: pointer;
- }
- </style>
- <script>
- /**
- * 地图的底图服务模块
- */
- var map_source = "wmts"; //地图的服务类型
- var map_projection = "EPSG:3857"; //地图坐标系(3857:墨卡托, 4326:经纬度)
- //map_url此处使用的是【Portable Basemap Server】作为地图服务
- var map_url = "http://localhost:7080/PBS/rest/services/lanzhou/MapServer/WMTS/tile/1.0.0/lanzhou/default/nativeTileMatrixSet/{z}/{y}/{x}.png";
- //var map_dataLayer = "layer_tdt_sl"; //地图服务的图层
- var map_zoom = 15; //初始化地图缩放级别
- var map_minZoom = 14; //地图最小缩放级别
- var map_maxZoom = 20; //地图最大缩放级别
- var map_x = 11557761.4071486; //地图x坐标(此处以兰州地图作为中心点)
- var map_y = 4307993.90607275; //地图y坐标(此处以兰州地图作为中心点)
- $(document).ready(function() {
- var baseLayer = new ol.layer.Tile({
- opacity: 1.0,
- source: new ol.source.XYZ({
- url: map_url
- })
- });
- if(baseLayer) {
- var config = {
- center: [map_x, map_y],
- zoom: map_zoom,
- maxZoom: map_maxZoom,
- minZoom: map_minZoom
- };
- //实例化标绘地图
- MYMAP.init(baseLayer, config);
- }
- //一定要把坐标从字符串类型转换为float类型
- var peopleLng = parseFloat("11557866.6091486");
- var peopleLat = parseFloat("4307896.40907275");
- var peoplePoint = new ol.geom.Point([peopleLng, peopleLat]);
- var projection = MYMAP.map.getView().getProjection();
- var peopleFeature = new ol.Feature({
- geometry: peoplePoint,
- labelPoint: peoplePoint,
- name: "people"
- });
- peopleFeature.set("res_type", "people"); //设置坐标点的图标
- peopleFeature.set("name", "people");
- peopleFeature.setId("people2017010720");
- MYMAP.vectorSource.addFeature(peopleFeature);
- //一定要把坐标从字符串类型转换为float类型
- var taxiLng = parseFloat("11556866.6091486");
- var taxiLat = parseFloat("4307696.40907275");
- var taxiPoint = new ol.geom.Point([taxiLng, taxiLat]);
- var projection = MYMAP.map.getView().getProjection();
- var taxiFeature = new ol.Feature({
- geometry: taxiPoint,
- labelPoint: taxiPoint,
- name: "taxi"
- });
- taxiFeature.set("res_type", "taxi"); //设置坐标点的图标
- taxiFeature.set("name", "taxi");
- taxiFeature.setId("taxi2017010720");
- MYMAP.vectorSource.addFeature(taxiFeature);
- //一定要把坐标从字符串类型转换为float类型
- var videoLng = parseFloat("11557761.4071486");
- var videoLat = parseFloat("4307993.90607275");
- var videoPoint = new ol.geom.Point([videoLng, videoLat]);
- var projection = MYMAP.map.getView().getProjection();
- var videoFeature = new ol.Feature({
- geometry: videoPoint,
- labelPoint: videoPoint,
- name: "video"
- });
- videoFeature.set("res_type", "video"); //设置坐标点的图标
- videoFeature.set("name", "video");
- videoFeature.setId("video2017010720");
- MYMAP.vectorSource.addFeature(videoFeature);
- MYMAP.map.getView().setCenter(videoFeature.getGeometry().getCoordinates());
- // 弹出窗口关闭
- $("#popup-closer").click(function(){
- MYMAP.overlay.setPosition(undefined);
- });
- //移动车辆
- $("#moveTaxi").click(function(){
- var newPoint = new ol.geom.Point([11556866.6091486,4308696.40907275]);
- var newFeature = MYMAP.vectorSource.getFeatureById("taxi2017010720");
- if(newFeature){
- newFeature.setGeometry(newPoint);//更新图层坐标
- if(MYMAP.overlayID == "taxi2017010720"){
- //定位弹出框的中心点-开始
- var geometry = newFeature.getGeometry();
- var coord = geometry.getCoordinates();
- MYMAP.overlay.setPosition(coord);
- //定位弹出框的中心点-结束
- }
- MYMAP.map.getView().setCenter(newFeature.getGeometry().getCoordinates());//重新定位地图的中心點
- }
- });
- });
- </script>
- <body>
- <!-- 地图对象 -->
- <div id="map" class="map">
- <div id="popup" class="ol-popup">
- <div id="popup-title" class="ol-popup-title"></div>
- <a href="#" id="popup-closer" class="ol-popup-closer"></a>
- <div id="popup-content" class="ol-popup-content"></div>
- </div>
- </div>
- <!--图层移动-->
- <button id="moveTaxi">移动车辆</button>
- </body>
- </html>
MYMap.js
- var MYMAP = {
- map: null, // 地图对象
- overlayID: null,//作为一个全局变量,用于保存弹出对象的featureid
- vectorSource: new ol.source.Vector({
- wrapX: false
- }),
- vectorLayer: null,
- icon: {
- "people": "images/people.png",
- "taxi": "images/taxi.png",
- "video": "images/video.png"
- },
- // 图上资源样式处理
- getStyle: function(_feature, _resolution) {
- return [new ol.style.Style({
- stroke: new ol.style.Stroke({
- color: 'red',
- width: 2
- }),
- image: new ol.style.Icon({
- offset: [0, 0],
- opacity: 1.0,
- rotateWithView: true,
- rotation: 0.0,
- scale: 1.0,
- size: [40, 40],
- src: MYMAP.icon[_feature.get("res_type")] //根據res_type的值来决定显示的图标
- })
- })];
- },
- init: function(_layer, _config) {
- MYMAP.vectorLayer = new ol.layer.Vector({
- source: MYMAP.vectorSource,
- style: MYMAP.getStyle,
- zIndex: 1000
- });
- // 初始弹出窗口对象
- MYMAP.overlay = new ol.Overlay(({
- element: document.getElementById("popup"),
- offset: [-5, -15],
- positioning: "center-right",
- autoPan: true,
- autoPanAnimation: {
- duration: 250
- }
- }));
- // 初始地图对象
- MYMAP.map = new ol.Map({
- layers: [_layer],
- loadTilesWhileAnimating: true,
- target: document.getElementById("map"),
- controls: ol.control.defaults({
- attributionOptions: ({
- collapsible: false
- })
- }),
- overlays: [MYMAP.overlay],
- view: new ol.View({
- center: _config.center,
- zoom: _config.zoom,
- maxZoom: _config.maxZoom,
- minZoom: _config.minZoom,
- }),
- interactions: ol.interaction.defaults({
- doubleClickZoom: false
- })
- });
- MYMAP.map.addLayer(MYMAP.vectorLayer);
- //初始化地图上的点击事件
- MYMAP.map.on("click", function(_e) {
- var feature = MYMAP.map.forEachFeatureAtPixel(_e.pixel, function(
- feature, layer) {
- return feature;
- });
- MYMAP.popup(feature);
- });
- },
- //资源弹出窗
- popup: function(_feature) {
- if(_feature) {
- var type = _feature.get("name") ? _feature.get("name") : "unknow";
- //定位弹出框的中心点-开始
- var geometry = _feature.getGeometry();
- var coord = geometry.getCoordinates();
- MYMAP.overlay.setPosition(coord);
- //定位弹出框的中心点-结束
- MYMAP.overlayID = _feature.getId();
- var titleHtml = "",
- html = "";
- switch(type) {
- case "people":
- var titleHtml = "人员信息:";
- titleHtml += " ";
- titleHtml += "";
- $("#popup-title").html(titleHtml);
- html += "人员编号:" + _feature.getId();
- $("#popup-content").html(html);
- break;
- case "taxi":
- var titleHtml = "出租车信息:";
- titleHtml += " ";
- titleHtml += "";
- $("#popup-title").html(titleHtml);
- html += "出租车编号:" + _feature.getId();
- $("#popup-content").html(html);
- break;
- case "video":
- var titleHtml = "摄像头信息:";
- titleHtml += " ";
- titleHtml += "";
- $("#popup-title").html(titleHtml);
- html += "摄像机编号:" + _feature.getId();
- $("#popup-content").html(html);
- break;
- }
- }
- }
- }
4、手工定位
04手工定位.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>04手工定位</title>
- <meta http-equiv="X-UA-Compatible" content="chrome=1">
- <link href="css/common/ol.css" rel="stylesheet" type="text/css" />
- <link href="css/04手工定位/map.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="js/common/ol.js"></script>
- <script type="text/javascript" src="js/common/jquery-1.11.2.min.js"></script>
- <script type="text/javascript" src="js/04手工定位/MYMap.js" ></script>
- <script type="text/javascript" src="js/04手工定位/marker.js" ></script>
- </head>
- <script>
- /**
- * 地图的底图服务模块
- */
- var map_source = "wmts"; //地图的服务类型
- var map_projection = "EPSG:3857"; //地图坐标系(3857:墨卡托, 4326:经纬度)
- //map_url此处使用的是【Portable Basemap Server】作为地图服务
- var map_url = "http://localhost:7080/PBS/rest/services/lanzhou/MapServer/WMTS/tile/1.0.0/lanzhou/default/nativeTileMatrixSet/{z}/{y}/{x}.png";
- //var map_dataLayer = "layer_tdt_sl"; //地图服务的图层
- var map_zoom = 15; //初始化地图缩放级别
- var map_minZoom = 14; //地图最小缩放级别
- var map_maxZoom = 20; //地图最大缩放级别
- var map_x = 11557761.4071486; //地图x坐标(此处以兰州地图作为中心点)
- var map_y = 4307993.90607275; //地图y坐标(此处以兰州地图作为中心点)
- $(document).ready(function() {
- var baseLayer = new ol.layer.Tile({
- opacity: 1.0,
- source: new ol.source.XYZ({
- url: map_url
- })
- });
- if(baseLayer) {
- var config = {
- center: [map_x, map_y],
- zoom: map_zoom,
- maxZoom: map_maxZoom,
- minZoom: map_minZoom
- };
- //实例化标绘地图
- MYMAP.init(baseLayer, config);
- }
- //手工定位
- $("#manualPosition").click(function(){
- MARKER.marker();
- });
- });
- </script>
- <body>
- <!-- 地图对象 -->
- <div id="map" class="map"></div>
- <!--手工定位-->
- <button id="manualPosition">手工定位</button>
- </body>
- </html>
map.css
- #manualPosition {
- position: absolute;
- top: 5%;
- left: 5%;
- background-color: rgba(0, 60, 136, .5);
- color: white;
- }
- #manualPosition:hover {
- cursor: pointer;
- }
- .tooltip {
- position: relative;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 4px;
- color: white;
- padding: 4px 8px;
- opacity: 0.7;
- white-space: nowrap;
- }
- .tooltip-measure {
- opacity: 1;
- font-weight: bold;
- }
- .tooltip-static {
- background-color: #ffcc33;
- color: black;
- border: 1px solid white;
- font-weight: bold;
- }
- .tooltip-measure:before, .tooltip-static:before {
- border-top: 6px solid rgba(0, 0, 0, 0.5);
- border-right: 6px solid transparent;
- border-left: 6px solid transparent;
- content: "";
- position: absolute;
- bottom: -6px;
- margin-left: -7px;
- left: 50%;
- }
- .tooltip-static:before {
- border-top-color: #ffcc33;
- }
- .tooltip-static .show{
- display:block;
- position: absolute;
- right:0px;
- border:1px;
- border-color:#000000;
- border-radius:2px;
- top:-3px;
- cursor:pointer;
- }
- .tooltip-static .show:HOVER{
- background: gray;
- }
MYMAP.js
- var MYMAP = {
- map: null, // 地图对象
- init: function(_layer, _config) {
- // 初始地图对象
- MYMAP.map = new ol.Map({
- layers: [_layer],
- loadTilesWhileAnimating: true,
- target: document.getElementById("map"),
- controls: ol.control.defaults({
- attributionOptions: ({
- collapsible: false
- })
- }),
- view: new ol.View({
- center: _config.center,
- zoom: _config.zoom,
- maxZoom: _config.maxZoom,
- minZoom: _config.minZoom,
- }),
- interactions: ol.interaction.defaults({
- doubleClickZoom: false
- })
- });
- //添加手工定位标记图层
- MYMAP.map.addLayer(MARKER.markLayer());
- }
- }
marker.js【重点】
- /**
- * 手工定位
- */
- var MARKER = {
- //距离确认数据源
- source: new ol.source.Vector(),
- draw: null,
- closeElement: null, //关闭按钮
- spanElement: null, //显示数据(距离或是面积)
- measureTooltipElement: null,
- measureTooltip: null,
- //距离确认
- marker: function() {
- MARKER.clear();
- if(MARKER.draw) {
- MYMAP.map.removeInteraction(MARKER.draw);
- MARKER.draw = null;
- }
- MARKER.draw = new ol.interaction.Draw({
- source: MARKER.source,
- type: "Point",
- style: new ol.style.Style({
- image: new ol.style.Icon({
- offset: [0, 0],
- opacity: 1.0,
- rotateWithView: true,
- rotation: 0.0,
- scale: 1.0,
- size: [32, 32],
- src: "images/icons/marker.png"
- })
- })
- });
- MARKER.draw.on("drawstart", function(evt) {
- }, this);
- //手工定位结束后展示坐标信息
- MARKER.draw.on("drawend", function(evt) {
- MARKER.measureTooltipElement.className = 'tooltip tooltip-static';
- var feature = evt.feature;
- MARKER.sketch = null;
- MARKER.measureTooltipElement = null;
- MARKER.closeElement.style.display = 'block';
- MARKER.closeElement.className = 'show';
- MYMAP.map.un("pointermove", MARKER.pointerMoveHandler);
- MYMAP.map.removeInteraction(MARKER.draw);
- var posXY = document.getElementById("poxXY").innerText;
- var posXYArray = posXY.split(",");
- var XPos = posXYArray[0];
- var YPos = posXYArray[1];
- }, this);
- MYMAP.map.addInteraction(MARKER.draw);
- MARKER.createMeasureTooltip(); //创建显示信息的div
- MYMAP.map.on("pointermove", MARKER.pointerMoveHandler);
- },
- //清除所有数据
- clear: function() {
- MARKER.source.clear();
- MYMAP.map.removeOverlay(MARKER.measureTooltip);
- MYMAP.map.un("pointermove", MARKER.pointerMoveHandler);
- },
- //创建显示信息的div
- createMeasureTooltip: function() {
- if(MARKER.closeElement) {
- MARKER.closeElement.parentNode.removeChild(MARKER.closeElement);
- }
- if(MARKER.measureTooltipElement) {
- MARKER.measureTooltipElement.parentNode.removeChild(MARKER.measureTooltipElement);
- }
- MARKER.measureTooltipElement = document.createElement('div');
- MARKER.spanElement = document.createElement("span");
- MARKER.spanElement.id = "poxXY";
- MARKER.closeElement = document.createElement('span'),
- MARKER.closeElement.innerHTML = '✖';
- MARKER.closeElement.style.display = 'none';
- MARKER.closeElement.addEventListener('click', function() {
- MARKER.clear();
- }, false);
- MARKER.measureTooltipElement.appendChild(MARKER.closeElement);
- MARKER.measureTooltipElement.appendChild(MARKER.spanElement);
- MARKER.measureTooltipElement.className = 'tooltip tooltip-measure';
- MARKER.measureTooltip = new ol.Overlay({
- element: MARKER.measureTooltipElement,
- offset: [0, -25],
- positioning: 'bottom-center'
- });
- MYMAP.map.addOverlay(MARKER.measureTooltip);
- },
- //鼠标移动事件
- pointerMoveHandler: function(evt) {
- if(evt.dragging) {
- return;
- }
- var tooltipCoord = evt.coordinate;
- var output = tooltipCoord
- var msg = output[0].toFixed(6) + " , " + output[1].toFixed(6);
- MARKER.spanElement.innerHTML = msg;
- MARKER.measureTooltip.setPosition(evt.coordinate);
- },
- markLayer: function() {
- return new ol.layer.Vector({
- source: MARKER.source,
- style: new ol.style.Style({
- image: new ol.style.Icon({
- offset: [0, 0],
- opacity: 1.0,
- rotateWithView: true,
- rotation: 0.0,
- scale: 1.0,
- size: [32, 32],
- src: "images/icons/marker.png"
- })
- })
- });
- }
- }
5、画三圈和计算距离
05画三圈和计算距离.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>05画三圈和计算距离</title>
- <meta http-equiv="X-UA-Compatible" content="chrome=1">
- <link href="css/common/ol.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="js/common/ol.js"></script>
- <script type="text/javascript" src="js/common/jquery-1.11.2.min.js"></script>
- <script type="text/javascript" src="js/05画三圈和计算距离/MYMap.js" ></script>
- </head>
- <style>
- .ol-popup {
- position: absolute;
- background-color: white;
- padding-top: 5px;
- padding-left: 10px;
- padding-right: 10px;
- padding-bottom: 10px;
- border-radius: 2px;
- border: 1px solid #cccccc;
- bottom: 12px;
- left: -50px;
- }
- .ol-popup:after,
- .ol-popup:before {
- top: 100%;
- border: solid transparent;
- content: " ";
- position: absolute;
- }
- /*border-top-color:用于制作三角形*/
- .ol-popup:after {
- border-top-color: white;
- border-width: 10px;
- left: 48px;
- margin-left: -10px;
- }
- .ol-popup:before {
- border-top-color: #cccccc;
- border-width: 11px;
- left: 48px;
- margin-left: -11px;
- }
- .ol-popup-title {
- border-bottom: 1px solid #cccccc;
- padding-bottom: 3px;
- }
- .ol-popup-content {
- margin-top: 8px;
- width:260px;
- }
- .ol-popup-closer {
- text-decoration: none;
- position: absolute;
- top: 5px;
- right: 10px;
- }
- .ol-popup-closer:after {
- content: "✖";
- }
- </style>
- <script>
- /**
- * 地图的底图服务模块
- */
- var map_source = "wmts"; //地图的服务类型
- var map_projection = "EPSG:3857"; //地图坐标系(3857:墨卡托, 4326:经纬度)
- //map_url此处使用的是【Portable Basemap Server】作为地图服务
- var map_url = "http://localhost:7080/PBS/rest/services/lanzhou/MapServer/WMTS/tile/1.0.0/lanzhou/default/nativeTileMatrixSet/{z}/{y}/{x}.png";
- //var map_dataLayer = "layer_tdt_sl"; //地图服务的图层
- var map_zoom = 17; //初始化地图缩放级别
- var map_minZoom = 14; //地图最小缩放级别
- var map_maxZoom = 20; //地图最大缩放级别
- var map_x = 11557761.4071486; //地图x坐标(此处以兰州地图作为中心点)
- var map_y = 4307993.90607275; //地图y坐标(此处以兰州地图作为中心点)
- $(document).ready(function() {
- var baseLayer = new ol.layer.Tile({
- opacity: 1.0,
- source: new ol.source.XYZ({
- url: map_url
- })
- });
- if(baseLayer) {
- var config = {
- center: [map_x, map_y],
- zoom: map_zoom,
- maxZoom: map_maxZoom,
- minZoom: map_minZoom
- };
- //实例化地图
- MYMAP.init(baseLayer, config);
- //画三圈
- MYMAP.dispose();
- }
- // 弹出窗口关闭
- $("#popup-closer").click(function(){
- MYMAP.overlay.setPosition(undefined);
- });
- });
- </script>
- <body>
- <!-- 地图对象 -->
- <div id="map" class="map">
- <div id="popup" class="ol-popup">
- <div id="popup-title" class="ol-popup-title"></div>
- <a href="#" id="popup-closer" class="ol-popup-closer"></a>
- <div id="popup-content" class="ol-popup-content"></div>
- </div>
- </div>
- </body>
- </html>
MYMAP.js
- var MYMAP = {
- map: null, // 地图对象
- overlay: null, // 地图弹出信息窗口
- sphere: new ol.Sphere(6378137), //6378137赤道半径,用于计算距离
- vectorSource: new ol.source.Vector({
- wrapX: false
- }),
- vectorLayer: null,
- icon: {
- "people": "images/people.png",
- "taxi": "images/taxi.png",
- "video": "images/video.png"
- },
- // 图上资源样式处理
- getStyle: function(_feature, _resolution) {
- return [new ol.style.Style({
- stroke: new ol.style.Stroke({
- color: 'red',
- width: 2
- }),
- image: new ol.style.Icon({
- offset: [0, 0],
- opacity: 1.0,
- rotateWithView: true,
- rotation: 0.0,
- scale: 1.0,
- size: [40, 40],
- src: MYMAP.icon[_feature.get("res_type")] //根據res_type的值来决定显示的图标
- })
- })];
- },
- init: function(_layer, _config) {
- MYMAP.vectorLayer = new ol.layer.Vector({
- source: MYMAP.vectorSource,
- style: MYMAP.getStyle,
- zIndex: 1000
- });
- // 初始弹出窗口对象
- MYMAP.overlay = new ol.Overlay(({
- element: document.getElementById("popup"),
- offset: [-5, -15],
- positioning: "center-right",
- autoPan: true,
- autoPanAnimation: {
- duration: 250
- }
- }));
- // 初始地图对象
- MYMAP.map = new ol.Map({
- layers: [_layer],
- loadTilesWhileAnimating: true,
- target: document.getElementById("map"),
- controls: ol.control.defaults({
- attributionOptions: ({
- collapsible: false
- })
- }),
- overlays: [MYMAP.overlay],
- view: new ol.View({
- center: _config.center,
- zoom: _config.zoom,
- maxZoom: _config.maxZoom,
- minZoom: _config.minZoom,
- }),
- interactions: ol.interaction.defaults({
- doubleClickZoom: false
- })
- });
- MYMAP.map.addLayer(MYMAP.vectorLayer);
- //初始化地图上的点击事件
- MYMAP.map.on("click", function(_e) {
- var feature = MYMAP.map.forEachFeatureAtPixel(_e.pixel, function(
- feature, layer) {
- return feature;
- });
- MYMAP.popup(feature);
- });
- },
- //资源弹出窗
- popup: function(_feature) {
- if(_feature) {
- var type = _feature.get("name") ? _feature.get("name") : "unknow";
- //定位弹出框的中心点-开始
- var geometry = _feature.getGeometry();
- var coord = geometry.getCoordinates();
- MYMAP.overlay.setPosition(coord);
- //定位弹出框的中心点-结束
- var titleHtml = "",
- html = "";
- switch(type) {
- case "people":
- var titleHtml = "人员信息:";
- titleHtml += " ";
- titleHtml += "";
- $("#popup-title").html(titleHtml);
- html += "人员坐标:" + coord;
- var distance = MYMAP.distance([11557761.4071486, 4307993.90607275], coord);
- html += "与出租车(中心点)距离为:" + distance;
- $("#popup-content").html(html);
- break;
- case "taxi":
- var titleHtml = "出租车信息:";
- titleHtml += " ";
- titleHtml += "";
- $("#popup-title").html(titleHtml);
- html += "出租车坐标为:" + coord;
- $("#popup-content").html(html);
- break;
- }
- }
- },
- //画三圈
- dispose: function() {
- var point = new ol.geom.Point([11557761.4071486, 4307993.90607275]);
- var taxiFeature = new ol.Feature({
- geometry: point,
- name: "taxi"
- });
- taxiFeature.set("res_type", "taxi");
- MYMAP.vectorSource.addFeature(taxiFeature);
- //画三圈开始
- //300: 代表圆的半径
- var circle300 = new ol.geom.Circle([11557761.4071486, 4307993.90607275], 300);
- var circle200 = new ol.geom.Circle([11557761.4071486, 4307993.90607275], 200);
- var circle100 = new ol.geom.Circle([11557761.4071486, 4307993.90607275], 100);
- var circleFeature300 = new ol.Feature({
- geometry: circle300
- });
- var style300 = new ol.style.Style({
- fill: new ol.style.Fill({
- color: 'rgba(50, 205, 50, 0.3)'
- }),
- stroke: new ol.style.Stroke({
- color: 'rgba(50, 205, 50, 0.6)',
- width: 2
- }),
- image: new ol.style.Circle({
- radius: 7,
- fill: new ol.style.Fill({
- color: '#ffcc33'
- })
- })
- });
- circleFeature300.setStyle(style300);
- MYMAP.vectorSource.addFeature(circleFeature300);
- var circleFeature200 = new ol.Feature({
- geometry: circle200
- });
- var style200 = new ol.style.Style({
- fill: new ol.style.Fill({
- color: 'rgba(255, 165, 0, 0.3)'
- }),
- stroke: new ol.style.Stroke({
- color: 'rgba(255, 165, 0, 0.6)',
- width: 2
- }),
- image: new ol.style.Circle({
- radius: 7,
- fill: new ol.style.Fill({
- color: '#ffcc33'
- })
- })
- });
- circleFeature200.setStyle(style200);
- MYMAP.vectorSource.addFeature(circleFeature200);
- var circleFeature100 = new ol.Feature({
- geometry: circle100
- });
- var style100 = new ol.style.Style({
- fill: new ol.style.Fill({
- color: 'rgba(255, 0, 0, 0.3)'
- }),
- stroke: new ol.style.Stroke({
- color: 'rgba(255, 0, 0, 0.6)',
- width: 2
- }),
- image: new ol.style.Circle({
- radius: 7,
- fill: new ol.style.Fill({
- color: '#ffcc33'
- })
- })
- });
- circleFeature100.setStyle(style100);
- MYMAP.vectorSource.addFeature(circleFeature100);
- //画三圈结束
- var pan = ol.animation.pan({
- duration: 500,
- source: (MYMAP.map.getView().getCenter())
- });
- MYMAP.map.beforeRender(pan);//延迟上图
- MYMAP.map.getView().setCenter(point.getCoordinates());
- //初始化三圈内的坐标点,用于计算
- var peopleFeature100 = new ol.Feature({
- geometry: new ol.geom.Point([11557696.316242, 4307946.730094]),
- name: "people"
- });
- peopleFeature100.set("res_type", "people");
- MYMAP.vectorSource.addFeature(peopleFeature100);
- var peopleFeature200 = new ol.Feature({
- geometry: new ol.geom.Point([11557628.239513, 4307988.531594]),
- name: "people"
- });
- peopleFeature200.set("res_type", "people");
- MYMAP.vectorSource.addFeature(peopleFeature200);
- var peopleFeature300 = new ol.Feature({
- geometry: new ol.geom.Point([11557937.570612, 4308199.927751]),
- name: "people"
- });
- peopleFeature300.set("res_type", "people");
- MYMAP.vectorSource.addFeature(peopleFeature300);
- },
- //用于计算两个坐标点之间的距离
- distance: function(point1, point2) {
- return MYMAP.sphere.haversineDistance(point1, point2);
- }
- }
6、三高四色地图
06三高四色地图.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>06三高四色预警</title>
- <meta http-equiv="X-UA-Compatible" content="chrome=1">
- <link href="css/common/ol.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="js/common/ol.js"></script>
- <script type="text/javascript" src="js/common/jquery-1.11.2.min.js"></script>
- </head>
- <script>
- /**
- * 地图的底图服务模块
- */
- var map_source = "wmts"; //地图的服务类型
- var map_projection = "EPSG:3857"; //地图坐标系(3857:墨卡托, 4326:经纬度)
- //map_url此处使用的是【Portable Basemap Server】作为地图服务
- var map_url = "http://localhost:8888/PBS/rest/services/lanzhou/MapServer/WMTS/tile/1.0.0/lanzhou/default/nativeTileMatrixSet/{z}/{y}/{x}.png";
- //var map_dataLayer = "layer_tdt_sl"; //地图服务的图层
- var map_zoom = 24; //初始化地图缩放级别
- var map_minZoom = 24; //地图最小缩放级别
- var map_maxZoom = 26; //地图最大缩放级别
- var map_x = 113.21413; //地图x坐标(此处以兰州地图作为中心点)113.21413,38.09156
- var map_y = 38.09156; //地图y坐标(此处以兰州地图作为中心点)
- $(document).ready(function() {
- var baseLayer = new ol.layer.Tile({
- opacity: 1.0,
- source: new ol.source.XYZ({
- url: map_url
- })
- });
- if(baseLayer) {
- // 初始地图对象
- var MYMAP = {
- map: null, // 地图对象
- vectorSource: new ol.source.Vector({
- wrapX: false
- }),
- vectorLayer: null
- }
- MYMAP.map = new ol.Map({
- layers: [baseLayer],
- loadTilesWhileAnimating: true,
- target: document.getElementById("map"),
- controls: ol.control.defaults({
- attributionOptions: ({
- collapsible: false
- })
- }),
- view: new ol.View({
- center: [map_x, map_y],
- zoom: map_zoom,
- minZoom: map_minZoom,
- maxZoom: map_maxZoom
- }),
- interactions: ol.interaction.defaults({
- doubleClickZoom: false
- })
- });
- MYMAP.vectorLayer = new ol.layer.Vector({
- source: MYMAP.vectorSource,
- zIndex: 1000
- });
- MYMAP.map.addLayer(MYMAP.vectorLayer);
- }
- var shapesArray = ['113.11466,38.42001,113.11438,38.42027','112.49035,37.12116,112.48808,37.12078'];
- var nameArray = ['太原市','大同市','朔州市','忻州市','阳泉市','晋中市','长治市','晋城市','吕梁市','临汾市','运城市'];
- for(var i = 0;i < shapesArray.length;i++){
- var geoAr= shapesArray[i].split(",");
- var geometryAr= [];
- for(var j=0; j<geoAr.length; j+=2){
- var lng= geoAr[j];
- var lat= geoAr[j+1];
- var point= [parseFloat(lng), parseFloat(lat)];
- geometryAr.push(point);
- }
- var geometry= new ol.geom.Polygon([geometryAr]);//创建一个多边形对象
- var feature= new ol.Feature({
- geometry: geometry
- });
- var style = new ol.style.Style({
- fill: new ol.style.Fill({//填充要素的样式
- color: 'rgba(253, 64, 139, 0.6)'
- }),
- stroke: new ol.style.Stroke({//要素边界样式
- color: 'blue',
- width: 2
- }),
- text:new ol.style.Text({ //文字格式
- textAlign:'center',
- textBaseline:'middle',
- font:'normal 14px 微软雅黑',
- text: nameArray[i],
- fill:new ol.style.Fill({color:'#000000'}),
- stroke:new ol.style.Stroke({color:'#ffcc33',width:2})
- })
- });
- feature.setStyle(style);
- MYMAP.vectorSource.addFeature(feature);
- }
- });
- </script>
- <body>
- <!-- 地图对象 -->
- <div id="map" class="map"></div>
- </body>
- </html>
附件源码:
链接:http://pan.baidu.com/s/1dEWNYH7 密码:7f0q