Getting distance(in kms) from map center to start/end position of map - Google Maps Javascript

爷,独闯天下 提交于 2021-02-18 18:59:39

问题


How can I get distance(in kms) from mapCenter() to start/end position of map using Google Maps Javascript? Is there a way to do this?


回答1:


You probably looking for a getBounds function:

Returns the lat/lng bounds of the current viewport. If more than one copy of the world is visible, the bounds range in longitude from -180 to 180 degrees inclusive. If the map is not yet initialized (i.e. the mapType is still null), or center and zoom have not been set then the result is null or undefined.

Then you could utilize Geometry Library in particular google.maps.geometry.spherical.computeDistanceBetween function to calculate distance between two points (in meters by default).

Example

function initialize() {
    var center = new google.maps.LatLng(55.755327, 37.622166);

    var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    google.maps.event.addListener(map, 'bounds_changed', function() {
       var bounds = map.getBounds();
       var start = bounds.getNorthEast();
       var end = bounds.getSouthWest();
       var distStart = google.maps.geometry.spherical.computeDistanceBetween (center, start) / 1000.0;
       var distEnd = google.maps.geometry.spherical.computeDistanceBetween (center, end) / 1000.0;
      

       document.getElementById('output').innerHTML += 'Distiance from center to start:' + distStart; 
       document.getElementById('output').innerHTML += 'Distiance from center to end:' + distEnd + '<br/>'; 

    });
}

google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry"></script>
<div id="map" style="width: 500px; height: 350px;"></div>
<div id='output'/>


来源:https://stackoverflow.com/questions/32558185/getting-distancein-kms-from-map-center-to-start-end-position-of-map-google-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!