Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Get Coordinates of the google maps Corners?

I need to draw polygon with just four coordinates that is for the four corners of the loaded map in zoom 13 on other hand get coordinates of the whole map to show to user. ( user search the specific area with draw a polygon on the map but if he/she don't draw a polygon i want to draw a polygon in size of the projected map for him/her and show the result. )

like image 337
Amir Rezvani Avatar asked Oct 29 '15 06:10

Amir Rezvani


1 Answers

Create the map at zoom: 13

var map = new google.maps.Map(document.getElementById("map"), {
    center: {lat: 51.561162, lng: -0.163331},
    zoom: 13
});

Then use map.getBounds() to get the LatLngBounds of the visible map.

var bounds = map.getBounds();

You can then use this to get the LatLng coordinates of the South West and North East corners:

var NECorner = bounds.getNorthEast();
var SWCorner = bounds.getSouthWest();

Then you can use those to work out the coordinates for the other two corners:

var NWCorner = new google.maps.LatLng(NECorner.lat(), SWCorner.lng());
var SECorner = new google.maps.LatLng(SWCorner.lat(), NECorner.lng());

And finally draw the polygon, using those corners for the paths array:

var polygon = new google.maps.Polygon({
    map: map,
    paths: [NWCorner, NECorner, SECorner, SWCorner],
    fillColor: 'red',
    fillOpacity: 0.7
});
like image 133
duncan Avatar answered Oct 05 '22 11:10

duncan