简体   繁体   中英

Get width in kilometers of Google Maps API map

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.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM