首页 > 解决方案 > 在 Map v3 API 中无法计算距离(两个坐标之间,不考虑骑行、驾驶等旅行模式)

问题描述

我想要两个地址之间的确切地理距离,它在 v3 中的旅行模式中有所不同。请找到以下代码,我调用的 API 文件是 script type='text/javascript' src='//maps.googleapis.com/maps/api/js?key=xxxxxxxxxxx'

function showLocation(a,b)
    {  
     alert(a.value);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode(document.forms[0].address.value, function (response) { 
        if (!response || response.Status.code != 200)
        {
            alert("Sorry, we were unable to geocode the first address");
        }
        else
        { 
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
            geocoder.getLocations(a.value, function (response) {
                if (!response || response.Status.code != 200)
                {
                    alert("Sorry, we were unable to geocode the second address");
                }
                else
                {
                location2= {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                var x=calculateDistance();
                 b.value = x;    
                    }
        });
    }
});}

function calculateDistance(){
try
{
    var glatlng1 = new GLatLng(location1.lat, location1.lon);
    var glatlng2 = new GLatLng(location2.lat, location2.lon);
    var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(2);
    return miledistance;
}
catch (error)
{
     alert(error);
}}

标签: javascriptjqueryasp.net

解决方案


推荐阅读