Search code examples
google-mapsgoogle-maps-static-api

Specify a Google Maps Static image with borders/viewport specified by lat and lon coordinates


I am trying to request an image from the Google Static Maps API with the borders of the map specified by a pair of latitude and longitude coordinates. I've tried centering on the center of the two coordinates, but there doesn't seem to be any parameter for doing this with the Static API. Does anyone know how to do this?

Note: this is for a desktop application, and I am not using the Javascript API.


Solution

  • The thing is that you cannot base the request on the map's corners because 1. zoom levels are discrete values and 2. the amount of latitude that a pixel represents varies with latitude. So, to display 2 degrees you'll need a given map height near the equator and a different height, (greater), near the poles. Are you willing to display maps of different heights in order to fit always 2 degrees?

    If so, you can use the MercatorProjection object from my other post, and use the following function to calculate the necessary map size:

    <script src="MercatorProjection.js"></script>
    
    function getMapSize(center,zoom){
        var proj = new MercatorProjection();
        var scale = Math.pow(2,zoom);
        var centerPx = proj.fromLatLngToPoint(center);
        var SW = new google.maps.LatLng(center.lat()-1,center.lng()-1);
        var southzWestPx = proj.fromLatLngToPoint(SW);
        var NE = new google.maps.LatLng(center.lat()+1,center.lng()+1);
        var northEastPx = proj.fromLatLngToPoint(NE);
    
    // Then you can calculate the necessary width and height of the map:
        var mapWidth = Math.round((northEastPx.x - southzWestPx.x) * scale);
        var mapHeight = Math.round((southzWestPx.y - northEastPx.y) * scale); 
    }
    

    With center = new google.maps.LatLng(49.141404, -121.960988) and zoom = 7 you get that you need a map of (W x H) 182 x 278 pixels in order to display 2 x 2 degrees.