【问题标题】:Get user's location (latitude, longitude) with Bing or Google Maps API使用 Bing 或 Google Maps API 获取用户的位置(纬度、经度)
【发布时间】:2012-02-13 10:26:06
【问题描述】:

有没有办法使用 Bing Maps API 或 Google Maps API 检索用户的纬度和经度。我想我看到了一个代码 sn-p,其中使用“自动定位我”功能在地图本身上标记用户:

var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);  
geoLocationProvider.getCurrentPosition(); 

但是该函数不返回任何数据,它只是在地图上设置位置,而我需要该位置来执行一些计算,即计算预定义的地点列表中哪个最接近当前用户位置。除此之外,是否有任何 API 可以计算作为输入提供的两个位置(纬度、经度)之间的距离?

谢谢, 帕维尔

【问题讨论】:

    标签: google-maps geolocation bing-maps


    【解决方案1】:

    HTML5 GeoLocation 获取当前位置的经纬度。 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>
    

    【讨论】:

      【解决方案2】:

      获取您的位置不是 Map API 的一部分。相反,请使用HTML5 GeoLocation API 获取您的位置。一个例子是:

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

      要计算 lat/lng 点之间的距离,请查看 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;
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 2012-07-24
      相关资源
      最近更新 更多