JavaScript 使用标尺计算Google Map v3上的距离
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 使用标尺计算Google Map v3上的距离相关的知识,希望对你有一定的参考价值。
/*
javascript ruler for google maps V3
by Giulio Pons. http://www.barattalo.it
this function uses the label class from Marc Ridley Blog
*/
function addruler() {
var ruler1 = new google.maps.Marker({
position: map.getCenter() ,
map: map,
draggable: true
});
var ruler2 = new google.maps.Marker({
position: map.getCenter() ,
map: map,
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 = 6371; // km (change this constant to get miles)
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)+"km";
else if (d<=1) return Math.round(d*1000)+"m";
return d;
}
以上是关于JavaScript 使用标尺计算Google Map v3上的距离的主要内容,如果未能解决你的问题,请参考以下文章
通过JavaScript更改Photoshop中的标尺原点
Google Maps Javascript - 计算方向和指南针方向来计算朝向的方向
怎样将word标尺调出来?word标尺的使用技巧!
1018 Public Bike Management (30 分)(图的遍历and最短路径)
018 盒子实战
5.裁剪和切片(标尺使用)