Abraham Gnanasingh
Abraham Gnanasingh

Reputation: 907

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

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?

Upvotes: 1

Views: 2133

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59368

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'/>

Upvotes: 2

Related Questions