26

Possible Duplicate:
get current latlng bounds?

I'm looking for the best way to use the Google maps API to get the latitude and longitude of the map viewport. Ideally I'd like to be able to use the latitude of the map's upper and lower borders and the longitude of the sides. The idea is the figure out the area of the visible map and adjust some related elements on the page based on what's currently visible on the map. Is there a a function in the map's API that handles this?

Thanks, any help is much appreciated.

Salman A
  • 262,204
  • 82
  • 430
  • 521

2 Answers2

66

Map.getBounds() gives you the LatLngBounds of the current viewport. You can then use LatLngBounds.getNorthEast() and LatLngBounds.getSouthWest() to get north-east (top right) and south-west (bottom-left) coordinates as LatLng. More specifically:

var lat0 = map.getBounds().getNorthEast().lat();
var lng0 = map.getBounds().getNorthEast().lng();
var lat1 = map.getBounds().getSouthWest().lat();
var lng1 = map.getBounds().getSouthWest().lng();
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • @angry_kiwi grab the current bounds using `Map.getBounds()` and use `Map.fitBounds()` to set the visible area to those bounds sometime later. Here OP was interested in getting lat/lng coordinates of the corners so I skipped the fit-bounds part. – Salman A Sep 25 '15 at 19:58
  • If you need a single pair of coordinates (rather than bound set) to get the center of the current viewport you can use getCenter() function, described here: https://developers.google.com/maps/documentation/javascript/reference/3/map?hl=pt-BR#Map.getCenter – Jonny Jul 31 '18 at 14:20
4

Use method getBounds of the Map class.

HugoLemos
  • 473
  • 3
  • 16