Reputation: 53
How can I get the current width of the visible area on Google map, i have read many docs but not success? I need to get real width of visible area in kilometers.
Upvotes: 2
Views: 1438
Reputation: 241
I think getBounds() is what you are looking for.
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'idle', function(event) {
var bounds = map.getBounds();
You will receive a LatLngBounds object (for reference https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds).
This contains NortEase and SouthWest LatLng points. Using those it should be easy to get the width in kilometers using this formula. You can create 2 pairs out of LatLng points to create a NorthWest and NorthEast pair and calculate the distance between those.
var R = 6371000; // metres
var φ1 = lat1.toRadians();
var φ2 = lat2.toRadians();
var Δφ = (lat2-lat1).toRadians();
var Δλ = (lon2-lon1).toRadians();
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
See this as an reference (http://www.movable-type.co.uk/scripts/latlong.html).
Upvotes: 4