使用Google地图的测距功能

使用google地图API的测距功能 首先需要引入对应的Google地图的库(drawing,geometry,spherical)

引入方法在

<script src="https://maps.googleapis.com/maps/api/js?language=en&key=你的key&libraries=drawing,places,geometry,spherical">

这里的思路是:先划线然后取点 通过API进行测量距离显示结果

Step1 划线的准备工作

var _styleOptions = {
    strokeColor:"red",          //边线颜色。
    fillColor:"white",          //填充颜色。当参数为空时,圆形将没有填充效果。
	strokeWeight: 2,            //边线的宽度,以像素为单位。
	strokeOpacity: 0.5,         //边线透明度,取值范围0 - 1。
	fillOpacity: 0.5,           //填充的透明度,取值范围0 - 1。
	strokeStyle: 'solid'        //边线的样式,solid或dashed。
    };

//划线完成后的事件
google.maps.event.addListener(_drawingManager, 'polylinecomplete', function(polyline) {
    var pointxy = polyline.getPath();
    var triangleCoords= [];
	for(var i=0; i<pointxy.length;i++){
		var pointstemp =  new google.maps.LatLng(pointxy.getAt(i).lat(),             pointxy.getAt(i).lng());
		triangleCoords.push(pointstemp);
	}
			
    //直接调用API接口来计算几条线段的长度和 单位米
	var distanceValue = google.maps.geometry.spherical.computeLength(triangleCoords);
	distanceValue = (distanceValue/1000).toFixed(2);
	distanceValue += "Km";
	var marker = new google.maps.Marker({
	    map: _map,
		position: triangleCoords[triangleCoords.length-1],
		label: distanceValue
	});
				
   });

Step2 触发Step1的条件(具体功能入口)

 function testDistance(){    
    _drawingManager.setMap(_map);
    _drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE);
 }

效果图:

111

这样就基本实现了这个功能,折线也可以计算;

猜你喜欢

转载自blog.csdn.net/Wuzm_/article/details/102520986