Amir Rezvani
Amir Rezvani

Reputation: 1504

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

Upvotes: 5

Views: 8418

Answers (2)

nawaab saab
nawaab saab

Reputation: 1902

Thanks duncan Lemme write it in short form for Kotlin developers

var bounds = googleMap!!.projection.visibleRegion.latLngBounds
var neCorner = bounds.northeast
var swCorner = bounds.southwest
var nwCorner = LatLng(neCorner.latitude, swCorner.longitude)
var seCorner = LatLng(swCorner.latitude, neCorner.longitude)

Upvotes: 4

duncan
duncan

Reputation: 31912

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
});

Upvotes: 19

Related Questions