Get user's location (latitude, longitude) with Bing or Google Maps API

前端 未结 2 1913
别那么骄傲
别那么骄傲 2020-12-06 02:21

is there a way to retrieve a latitude & longitude of the user using Bing Maps API or Google Maps API. I think I saw an code snippet where a \"autolocate me\" feature was

相关标签:
2条回答
  • 2020-12-06 02:55

    Getting your location isn't part of the Map API. Instead, use the HTML5 GeoLocation API to get your location. An example would be:

     navigator.geolocation.getCurrentPosition(locationHandler);
    
     function locationHandler(position)
     {
       var lat = position.coords.latitude;
       var lng = position.coords.longitude;
     }
    

    For calculating distance between lat/lng points, have a look at http://www.movable-type.co.uk/scripts/latlong.html.

    // Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2011                   - www.movable-type.co.uk/scripts/latlong.html 
    // where R is earth’s radius (mean radius = 6,371km);
    // note that angles need to be in radians to pass to trig functions!
    var R = 6371; // km
    var dLat = (lat2-lat1).toRad();
    var dLon = (lon2-lon1).toRad();
    var lat1 = lat1.toRad();
    var lat2 = lat2.toRad();
    
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;
    
    0 讨论(0)
  • 2020-12-06 03:07

    HTML5 GeoLocation get lat and long of current location. http://www.w3schools.com/html/html5_geolocation.asp

    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo">Click the button to get your coordinates:</p>
    <button onclick="getLocation()">Try It</button>
    
    <script>
    var x = document.getElementById("demo");
    
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    
    function showPosition(position) {
        x.innerHTML="Latitude: " + position.coords.latitude + 
        "<br>Longitude: " + position.coords.longitude;  
    }
    </script>
    
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题