Kevin Pang
Kevin Pang

Reputation: 41442

Showing markers within bounding box using Google Maps API v3

I want to display a list of markers that are located within the map's bounding box. I have a basic implementation working that intercepts the map's "bounds_changed" event and fires off an AJAX request to my server with the lat/long coordinates of the map's southwest and northeast corners. This works for most scenarios, however I've found that this implementation breaks if the user pans too far east/west.

For instance, let's say the bounding box originally starts out as being the whole world (southwest corner: [-90, -180], northwest corner: [90, 180]). Then, if the user pans west 180 degrees, the bounding box becomes [-90, -360] / [90, 0]. This breaks my AJAX request because even though the whole world is still visible to the user, any markers with a longitude > 0 won't be returned by my database query.

What's the best way of handling this?

Upvotes: 0

Views: 3050

Answers (1)

Kasper Vesth
Kasper Vesth

Reputation: 4113

The simplest way to do this would be to test the latitude and longitude values when you receive them, and if they are bigger than the "real world" latitude and longitude, you simply make sure to get their corresponding values in the range [-90; 90] for longitude and [-180; 180] for longitude.

As a side note: If you want to spare all the ajax calls, you can do it with javascript instead. The google.maps.LatLngBounds class have a method called contains that checks whether a given latlng is in the bounds. You would then simply store all your markers in an array when you initialize the site and then iterate over them when the user pans and set their visible property to true if they are within the current bounds. You can get the current bounds by calling getBounds() on your map instance.

Using the method map.getBounds().contains() will also solve your problem without have to worrying about whether the user pans too far, since the API handles that for you.

Upvotes: 3

Related Questions