The main error you have in your code is that the width and height parameters of the static maps API should be in pixels. You are currently calculating the distance in meters and passing it to the URLs of static maps instead of pixels.
I created an example based on your sample code, and was able to create the correct static map URL. Please see my example. The distanceInPx function is the most important thing. Create a rectangle using the drawing manager and click the Show static map link. Also note that the Static Maps API is limited by the size of an image of 640x640 pixels in the standard layout, so you cannot create a link for large rectangles.
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 28.45765, lng: -16.363564}, zoom: 21, mapTypeId: google.maps.MapTypeId.SATELLITE }); var drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: google.maps.drawing.OverlayType.RECTANGLE, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: ['rectangle'] } }); drawingManager.setMap(map); google.maps.event.addListener(drawingManager, "rectanglecomplete", function(rectangle){ function distanceInPx(pos1, pos2) { var p1 = map.getProjection().fromLatLngToPoint(pos1); var p2 = map.getProjection().fromLatLngToPoint(pos2); var pixelSize = Math.pow(2, -map.getZoom()); var d = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y))/pixelSize; return Math.round(d); } var zoom = map.zoom; var centre = rectangle.getBounds().getCenter();
#map { height: 100%; } html, body { height: 95%; margin: 0; padding: 0; }
<div id="map"></div> <a id="staticLink" href="#" target="_blank" title="Show static map" style="display:none;">Show static map</a> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=drawing&callback=initMap" async defer></script>
This example is also available in jsbin: http://jsbin.com/humuko/edit?html,output
Hope this helps!
source share