25

I have the following code in which I would expect the contains method to return true, but it returns false:

var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(55.38942944437183, -2.7379201682812226),
    new google.maps.LatLng(54.69726685890506, -1.2456105979687226)
);

var center = bounds.getCenter();  // (55.04334815163844, -1.9917653831249726)

var x = bounds.contains(center);  // returns false

On the same page, where map is a reference to the Map object, the following code returns true as expected:

map.getBounds().contains(map.getBounds().getCenter())

Why might my call to bounds.contains be returning false?

3 Answers 3

47

Ah, brilliant. The google.maps.LatLngBounds constructor expects SouthWest and NorthEast LatLng parameters. I have somehow bungled up my coordinates and passed in NorthWest and SouthEast instead!

var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(54.69726685890506,-2.7379201682812226),
    new google.maps.LatLng(55.38942944437183, -1.2456105979687226)
);

var center = bounds.getCenter();  // still returns (55.04334815163844, -1.9917653831249726)

var x = bounds.contains(center);  // now returns true

Lesson learned: getCenter doesn't care if you created the LatLngBounds with NorthWest and SouthEast instead, but if you want contains to return a useful answer you better pass in the suggested SouthWest and NorthEast!

1
  • Thanks. Now that's a gotcha to look out for!
    – Jason
    Commented Oct 21, 2019 at 11:19
15

I guess its easier to try this. It works for me without having to worry about NE orSW

var bounds = new google.maps.LatLngBounds();
bounds.extend({lat: 54.69726685890506, lng: -2.7379201682812226});
bounds.extend({lat: 55.38942944437183, lng: -1.2456105979687226});
var center = bounds.getCenter();  // still returns {lat: 55.04334815163844, lng: -1.9917653831249726}
var x = bounds.contains(center);  // now returns true

I know this post is old, but I came searching for answers here, so thought of updating from what I have learnt.

2
  • Yes, this is a much more productive and less confusing solution. Commented Aug 6, 2013 at 15:12
  • 6
    bounds.extend needs a LatLng object, not just numbers.
    – Sharky
    Commented Aug 18, 2014 at 9:45
2

This is the way that it worked for me:

var bounds = new google.maps.LatLngBounds();
bounds.extend(54.69726685890506,-2.7379201682812226);
bounds.extend(55.38942944437183, -1.2456105979687226); 
map.fitBounds(bounds);    
1
  • This worked for me, but like Sharky said the coords must be a LatLng object, not just numbers. ie: ` myLatLang = new google.maps.LatLng(54.69726685890506,-2.7379201682812226); bounds.extend(myLatLang ); `
    – JBS
    Commented Aug 31, 2015 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.