Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Understanding Google Maps "fitBounds" method

I just want to clarify whether my way of understanding is correct. In my Google Maps app I would like to show to my users markers from particular continents.

Question: Am I right that a bound in Google Map API is an area made from NOT MORE AND NOT LESS than two points (markers)?

From math lessons, to draw 2D area I just need two points. Right? So to show to my users all markers from Europe should I just find two coordinates, one from Iceland (top, left) and second from let's say south-east Turkey? (For USA I would pick Seattle and Miami).

enter image description here

So, below JS code works perfectly. My question is - could you confirm that my way of understanding and the approach I've chosen is correct? Does it make any sense?

var bounds = new google.maps.LatLngBounds();

bounds.extend(new google.maps.LatLng('66.057878', '-22.579047')); // Iceland
bounds.extend(new google.maps.LatLng('37.961952', '43.878878')); // Turkey

this.map.fitBounds(bounds);

Upvotes: 4

Views: 11096

Answers (2)

MrUpsidown
MrUpsidown

Reputation: 22493

You should not think about "top-left" and "bottom-right" but as south-west and north-east (so bottom-left and top-right if you like), as these are the coordinates used to create and/or retrieve the bounds object.

See the documentation and the getNorthEast and getSouthWest methods.

These two points are LatLng objects, and not markers. As an example, a marker is positioned on the map using a LatLng object.

I don't know your use case and your way of storing the data, but there might be a more precise way to display "Europe" markers. You could for example save the region along with each marker so that you can just query for "EU" markers and not others...

Upvotes: 1

TomLingham
TomLingham

Reputation: 331

Yes, you are mostly correct. Except a 'bound' in Google maps case can include multiple points, for example if you had a point to the far right in the middle of the square in your image above and another at the bottom of the square in the middle you would still get an area the same as you have drawn above but with 3 points as in the edited map.

Map showing bounds with 3 points

Obligatory link to the docs :) https://developers.google.com/maps/documentation/javascript/reference?hl=en

Upvotes: 3

Related Questions