下面我有一个代码,当用户点击标记时,它将显示谷歌位置 API 数据。
我也有一个坐标(lat,lng)的两点位置,所以Point1[], Point2[]
我如何计算以公里为单位的道路距离和这些地方之间的时间并以 HTML 格式显示。谷歌地图有计算这个距离和时间的功能吗?
代码:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
//class m_tooltip
var contentStr = '<div><h5>'+place.name+'</h5><p>'+place.formatted_address+'</p>';
if (!!place.photos) contentStr += '<img src='+place.photos[0].getUrl({ 'maxWidth': 500, 'maxHeight': 500 })+'></img>';
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
var Point1 = [34,666, 56,888];
var Point2 = [77.876, 45,555];
contentStr += '<p>Distance in km:' + functionThatReturnRoadDistance(Point1, Point2) + '</p>';
$(contentStr).dialog({
modal:true
});
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
$(contentStr).dialog();
}
});
那么是否有一些谷歌地图或类似功能会返回以米或公里为单位的距离,而不是地方之间的简单距离,而是道路/路线距离?
更新:我相信这个:
function calculateDistances(start,stop) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [start],
destinations: [stop],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var xxx= "";
xxx += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
return xxx;
}
}
}
}
并调用它:
var start = document.getElementById("from").value;
var stop = place.formatted_address;
contentStr += '<p>'+ calculateDistances(start,stop); + '</p>';
$(contentStr).dialog({
modal:true
});
但不要使用 DistanceMatrix