Google Maps API v3 - Geocoder results issue with bounds

喜欢而已 提交于 2019-11-28 18:26:42

Right. After trying both methods and testing, it comes out that:

  1. the geometry.bounds object is "optionnaly returned" as the doc says
  2. we don't exactly know what the geometry.bounds object is based on
  3. geometry.bounds "may not match the recommended viewport" and often doesn't
  4. geometry.bounds returns a square or rectangle of any size and shape while the viewport functions always return a rectangle with the same aspect ratio (around 1.43), whatever your map container dimensions are, as far as I tested.

Below is the example of San Francisco, CA, mentioned in the doc.
In red using geometry.bounds and in blue using the viewport functions.

The solution is simple enough and is reliable.

var resultBounds = new google.maps.LatLngBounds(

    results[0].geometry.viewport.getSouthWest(), 
    results[0].geometry.viewport.getNorthEast()
);

map.fitBounds(resultBounds);

The viewport object has the information you need to make a bounds object. Something like this:

var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(results[0].geometry.viewport.southwest.lat, results[0].geometry.viewport.southwest.lng),
    new google.maps.LatLng(results[0].geometry.viewport.northeast.lat, results[0].geometry.viewport.northeast.lng)
);

Then you can use fitBounds on that new bounds object, just like you're doing for the returned bounds object. Like this:

map.fitBounds(bounds);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!