h5实现点击定位并在地图上面标记(高德地图)

829 阅读1分钟

最近在开发h5 网页使用到了高德地图 记录一下踩坑经历

  • 高德地图如果想实现精准定位需要配置密钥
<script>
window._AMapSecurityConfig = {
    securityJsCode: 'xxxxxx',
}
</script>
  • 高德地图点击定位默认给用户的标记是无法清理的,需要开发者自定义标记去实现定位

浏览器精确定位-定位-示例中心-JS API 2.0 示例 | 高德地图API (amap.com)


let lastPositionMarker; 
// 定位函数  
let geolocation = null
let demoMarker = null
function getPosition() {
    if(lastPositionMarker) {
        lastPositionMarker.setMap(null)
        lastPositionMarker = null
    }
    if(demoMarker) {
        demoMarker.setMap(null)
        demoMarker = null
    }
     
    AMap.plugin(["AMap.Geolocation"], function() {
        
        geolocation = new AMap.Geolocation({  
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 10000,          //超过10秒后停止定位,默认:5s
            position:'RB',    //定位按钮的停靠位置
            offset: [10, 20], //定位按钮与设置的停靠位置的偏移量,默认:[10, 20]
            zoomToAccuracy: true, 
            'showCircle': true,//是否显示定位精度圈
        });
        console.log(geolocation.position)
        // map.addControl(geolocation);
        geolocation.getCurrentPosition();   
        
        lastPositionMarker  = new AMap.Marker({
            'offset': new AMap.Pixel(-8.5, -8.5),
            content: `<div class="amap-marker" >
                <img class="amap-geolocation-marker" src="https://a.amap.com/jsapi/static/image/plugin/point.png">
            </div>`,
            position: [113.665412, 34.757975], // 定位结果中的位置  
            map: map,
        });  


        demoMarker = new AMap.CircleMarker({
        	center:  [113.665412, 34.757975], // 定位结果中的位置
        	radius: 30,
        	bubble: true,
        	strokeColor: '#0093FF',
        	noSelect: true,
        	strokeOpacity: 0.5,
        	strokeWeight: 1,
        	fillColor: '#02B0FF',
        	fillOpacity: 0.25,
        	map: map
        })

        map.setFitView(demoMarker);
    })
  
   
    
}  



官方给的案例 image.png

自定义实现 image.png

完毕