openlayer 简单实用


做web地图的一个功能,之前用的arcgis,今天同事推荐了openlayer v4.x。简单记录一下。
用法大致跟arcgis差不多,感觉api没有arcgis的方便好用。
代码:
引入css js

<link rel="stylesheet" href="css/ol.css" type="text/css">
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/ol.js" type="text/javascript"></script>

页面内容

<input type="text" id="lon" name="" value="116.784172">
<input type="text" id="lat" name="" value="35.930695">
<input type="button" name="" value="locate" onclick="locate()">
<div id="map" class="map"></div>

初始化地图

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([116.412253,39.90923]),
        zoom: 8
    })
});

添加鼠标点击事件

map.addEventListener("click", function(e) {
    console.log(e);
    var cord = e.coordinate;
    var pos = ol.proj.transform(cord, 'EPSG:3857', 'EPSG:4326');
    alert("lon = "+pos[0]+" \nlat = "+pos[1]);
});

根据经纬度定位(应该还有其他定位fun?大神指点)

function locate(){
    var cord = [$("#lon").val()*1,$("#lat").val()*1];
    map.setView(new ol.View({
        center: ol.proj.fromLonLat(cord),
        zoom: 8
    }));
    var pos = ol.proj.transform(cord, 'EPSG:4326', 'EPSG:3857');
    addMarker(pos);
}

最后添加一个标注

function addMarker(cord) {
     var markerFeature = new ol.Feature({
         geometry: new ol.geom.Point(cord)
     });

     var markerStyle = new ol.style.Style({
         image: new ol.style.Icon(({
             anchor: [0.5,1],
             src: 'image/pointer.png'
         }))
     });
     markerStyle.getImage().setScale(0.3);
     markerFeature.setStyle(markerStyle);

     var vectorSource = new ol.source.Vector({
         features: [markerFeature]
     });

     var vectorLayer = new ol.layer.Vector({
         source: vectorSource
     });

     map.addLayer(vectorLayer);

 }

转载自:https://blog.csdn.net/yuxianyang_csdn/article/details/78794109

You may also like...