正如您在图像中看到的,我绘制了多个邮政编码多边形。在多边形上,我选择了 2 个点,我正在计算距离。距离计算工作正常,但问题是距离条(黄色)在穿过绘制的多边形时没有出现。
图片网址:http: //imm.io/17MNl
我正在使用此解决方案进行距离计算。http://www.barattalo.it/examples/ruler.html
当我单击添加标记的按钮时调用 addruler() 函数,当我拖动标记以计算两点之间的距离时调用 distance()。
function addruler() {
var ruler1 = new google.maps.Marker({
position: map.getCenter() ,
map: map,
icon: distance_marker_image,
draggable: true
});
var ruler2 = new google.maps.Marker({
position: map.getCenter() ,
map: map,
icon: distance_marker_image,
draggable: true
});
var ruler1label = new Label({ map: map });
var ruler2label = new Label({ map: map });
ruler1label.bindTo('position', ruler1, 'position');
ruler2label.bindTo('position', ruler2, 'position');
var rulerpoly = new google.maps.Polyline({
path: [ruler1.position, ruler2.position] ,
strokeColor: "#FFFF00",
strokeOpacity: .7,
strokeWeight: 7
});
rulerpoly.setMap(map);
ruler1label.set('text',distance( ruler1.getPosition().lat(), ruler1.getPosition().lng(), ruler2.getPosition().lat(), ruler2.getPosition().lng()));
ruler2label.set('text',distance( ruler1.getPosition().lat(), ruler1.getPosition().lng(), ruler2.getPosition().lat(), ruler2.getPosition().lng()));
google.maps.event.addListener(ruler1, 'drag', function() {
rulerpoly.setPath([ruler1.getPosition(), ruler2.getPosition()]);
ruler1label.set('text',distance( ruler1.getPosition().lat(), ruler1.getPosition().lng(), ruler2.getPosition().lat(), ruler2.getPosition().lng()));
ruler2label.set('text',distance( ruler1.getPosition().lat(), ruler1.getPosition().lng(), ruler2.getPosition().lat(), ruler2.getPosition().lng()));
});
google.maps.event.addListener(ruler2, 'drag', function() {
rulerpoly.setPath([ruler1.getPosition(), ruler2.getPosition()]);
ruler1label.set('text',distance( ruler1.getPosition().lat(), ruler1.getPosition().lng(), ruler2.getPosition().lat(), ruler2.getPosition().lng()));
ruler2label.set('text',distance( ruler1.getPosition().lat(), ruler1.getPosition().lng(), ruler2.getPosition().lat(), ruler2.getPosition().lng()));
});
}
function distance(lat1,lon1,lat2,lon2) {
var R = 3959; // km (change this constant to get miles. 3959 for m, 6371 for km also change 1000 to 1760)
var dLat = (lat2-lat1) * Math.PI / 180;
var dLon = (lon2-lon1) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
if (d>1) return Math.round(d)+"miles";
else if (d<=1) return Math.round(d*1760)+"yards";
return d;
}