当对同一来源和目的地进行不同调用时,Google Distance API会给我不同的结果

Google Distance API giving me different results when called differently for the same source and destinations

本文关键字:API Distance Google 结果 调用 目的地      更新时间:2023-10-05

我正试图从googleapi中用两种不同的方法来找到两点p1和p2之间的距离。。。

这是代码。。。

var directionsService = new google.maps.DirectionsService();
        var p1 = new google.maps.LatLng(45.463688, 9.18814);
        var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);
        var request = {
            origin: p1,//'Melbourne VIC', // a city, full address, landmark etc
            destination: p2,// 'Sydney NSW',
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                console.log(response.routes[0].legs[0].distance.value/1000); // the distance in metres
                //console.log(response.routes[0].legs[0].duration.value);
            }
            else {
                // oops, there's no route between these two locations
                // every time this happens, a kitten dies
                // so please, ensure your address is formatted properly
            }
            console.log(calcDistance(p1, p2));
            //if(!(parseFloat("hello"))) console.log(parseFloat("12.222"));
            //calculates distance between two points in km's
            function calcDistance(p1, p2) {
                return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
            }
        });

我得到的输出如下。。。103.847//对于第一个日志78.35//对于第二个日志

有人能解释一下为什么会有这种差异吗。。。。我是不是搞错了。。。。

您使用的第一种方法是请求谷歌方向服务,当您将行驶模式设置为DRIVING时,该响应是道路上两点之间的一组方向。距离就是你必须行驶的距离。第二种方法是返回几何体库,返回球体上的最短路径,即两点之间的世界(大圆距离)。因此,距离2更短,因为它是直接的,而距离1是假设你想使用道路的实际行驶距离。