javascript 带地理定位的谷歌地图距离计算器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12911204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:25:30  来源:igfitidea点击:

Google Maps distance calculator WITH geolocation

javascriptgeolocationmaps

提问by user1749428

I have a small web app that can calculate the distance between two points on Google maps.

我有一个小型网络应用程序,可以计算谷歌地图上两点之间的距离。

I would like it to place the user at it's current position when loading the app. I have tried with different geolocation methods without any luck.

我希望它在加载应用程序时将用户置于当前位置。我尝试过不同的地理定位方法,但没有任何运气。

The best thing would be to have it calculate the distance from the users position. However, just having the users position in the web-app will be enough for me.

最好的办法是让它计算与用户位置的距离。但是,仅让用户在网络应用程序中的位置对我来说就足够了。

<html>
    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">

    var directionDisplay;
    var map;


function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var copenhagen = new google.maps.LatLng(55.6771, 12.5704);
    var myOptions = {
        zoom:12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: copenhagen
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    }


    var directionsService = new google.maps.DirectionsService();

    function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var distanceInput = document.getElementById("distance");

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
        }
    });
    }
    </script>

    <title>Distance Calculator</title>

    <style type="text/css">

            body {
                font-family:Helvetica, Arial;
            }
            #map_canvas {
                height: 50%;
            }
    </style>
    </head>
    <body>

    <body onload="initialize()">
    <p>Enter your current location and desired destination to get the distance</p>
        <div>
            <p>
                <label for="start">Start: </label>
                <input type="text" name="start" id="start" />

                <label for="end">End: </label>
                <input type="text" name="end" id="end" />

                <input type="submit" value="Calculate Route" onclick="calcRoute()" />
            </p>
            <p>
                <label for="distance">Distance (km): </label>
                <input type="text" name="distance" id="distance" readonly="true" />
            </p>
        </div>
        <div id="map_canvas"></div>
    </body>
</html>

回答by Pragnesh Chauhan

you need to try this link

你需要试试这个链接

google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
// setup our variables
var lat1 = this.lat();
var radianLat1 = lat1 * ( Math.PI  / 180 );
var lng1 = this.lng();
var radianLng1 = lng1 * ( Math.PI  / 180 );
var lat2 = newLatLng.lat();
var radianLat2 = lat2 * ( Math.PI  / 180 );
var lng2 = newLatLng.lng();
var radianLng2 = lng2 * ( Math.PI  / 180 );
// sort out the radius, MILES or KM?
var earth_radius = 3959; // (km = 6378.1) OR (miles = 3959) - radius of the earth

// sort our the differences
var diffLat =  ( radianLat1 - radianLat2 );
var diffLng =  ( radianLng1 - radianLng2 );
// put on a wave (hey the earth is round after all)
var sinLat = Math.sin( diffLat / 2  );
var sinLng = Math.sin( diffLng / 2  ); 


var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);

// work out the distance
var distance = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));

// return the distance
return distance;
}

distance-finder-google-maps-api

distance-finder-google-maps-api

回答by Stouffi

To get the user's position using javascript :

使用 javascript 获取用户的位置:

var showPosition = function (position) {
    var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    // Do whatever you want with userLatLng.
}
navigator.geolocation.getCurrentPosition(showPosition); // Attach showPosition Callback which will be executed as soon as position is available. Remember it needs user confirmation.

See http://jsfiddle.net/Stouffi/FCFSW/, for example.

例如,请参见http://jsfiddle.net/Stouffi/FCFSW/

UPDATE:

更新:

Youd need to change the onclick callback of your calcRoute button. The new one will request user's position. Once position is acquired, calcRoute is called.

您需要更改 calcRoute 按钮的 onclick 回调。新的将请求用户的位置。获取位置后,将调用 calcRoute。

function findCurrentLocation() {
    navigator.geolocation.getCurrentPosition(calcRoute);
}

In calcRoute, position object will be available as argument, you need to convert him into a LatLng object to deal with google directions service.

在 calcRoute 中,位置对象将作为参数可用,您需要将他转换为 LatLng 对象来处理谷歌路线服务。

function calcRoute(currentLocation) {
    // create a LatLng object from the position object.
    var start = new google.maps.LatLng(currentLocation.coords.latitude, currentLocation.coords.longitude);
    // Continue with your original code.
    var end = document.getElementById("end").value;
    // etc.

See http://jsfiddle.net/Stouffi/mCYTf/

http://jsfiddle.net/Stouffi/mCYTf/