ChatGPT解决这个技术问题 Extra ChatGPT

Google Map API v3 — set bounds and center

I've recently switched to Google Maps API V3. I'm working of a simple example which plots markers from an array, however I do not know how to center and zoom automatically with respect to the markers.

I've searched the net high and low, including Google's own documentation, but have not found a clear answer. I know I could simply take an average of the co-ordinates, but how would I set the zoom accordingly?

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),


    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

  setMarkers(map, beaches);
}


var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.423036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 121.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.450198, 151.259302, 1]
];

function setMarkers(map, locations) {

  var image = new google.maps.MarkerImage('images/beachflag.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
    var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',

      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));


      var lat = map.getCenter().lat(); 
      var lng = map.getCenter().lng();      


  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

K
Kevin Workman

Yes, you can declare your new bounds object.

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

Then for each marker, extend your bounds object:

bounds.extend(myLatLng);
map.fitBounds(bounds);

API: google.maps.LatLngBounds


you may also add this map.setCenter(bounds.getCenter());
Both the answer and the comment by Raman helped whittle down my focus on what I needed.
@Sam152: you might be interested in a 500 rep bounty for a related question.
Why fire map.fitBounds(bounds); every time a point is added, rather than just once at the end?
c
cincodenada

Got everything sorted - see the last few lines for code - (bounds.extend(myLatLng); map.fitBounds(bounds);)

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(
    document.getElementById("map_canvas"),
    myOptions);
  setMarkers(map, beaches);
}

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 161.259052, 5],
  ['Cronulla Beach', -36.028249, 153.157507, 3],
  ['Manly Beach', -31.80010128657071, 151.38747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.159302, 1]
];

function setMarkers(map, locations) {
  var image = new google.maps.MarkerImage('images/beachflag.png',
    new google.maps.Size(20, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
    new google.maps.Size(37, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shape = {
    coord: [1, 1, 1, 20, 18, 20, 18 , 1],
    type: 'poly'
  };
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      shadow: shadow,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3]
    });
    bounds.extend(myLatLng);
  }
  map.fitBounds(bounds);
}

Thanks! The 3.0 documents are surprisingly vague about where this functionality went.
The 3.0 documents are surprisingly vague about where a LOT of things went. :(
Sorry this is in the wrong place. It's meant to be a comment for the selected answer. But doesn't the extend function need to be inside your for loop?
Hello, great code but could this code be enhanced to avoid the "no images available at this zoom level". because this code doesn't take care of the zoom level, sure it does show all markers, but personnaly I'd prefer to see lower zoom to avoid the "no images ..." messages. Any idea please?
Are these "bounds.extend(myLatLng); map.fitBounds(bounds);" available for Android as well?
H
Hossein

The answers are perfect for adjust map boundaries for markers but if you like to expand Google Maps boundaries for shapes like polygons and circles, you can use following codes:

For Circles

bounds.union(circle.getBounds());

For Polygons

polygon.getPaths().forEach(function(path, index)
{
    var points = path.getArray();
    for(var p in points) bounds.extend(points[p]);
});

For Rectangles

bounds.union(overlay.getBounds());

For Polylines

var path = polyline.getPath();

var slat, blat = path.getAt(0).lat();
var slng, blng = path.getAt(0).lng();

for(var i = 1; i < path.getLength(); i++)
{
    var e = path.getAt(i);
    slat = ((slat < e.lat()) ? slat : e.lat());
    blat = ((blat > e.lat()) ? blat : e.lat());
    slng = ((slng < e.lng()) ? slng : e.lng());
    blng = ((blng > e.lng()) ? blng : e.lng());
}

bounds.extend(new google.maps.LatLng(slat, slng));
bounds.extend(new google.maps.LatLng(blat, blng));

l
localtime

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt


Instead of returning false if the bounds are null, you could maps[ mapId ].getBounds().
@localtime actually, your web site needs Google Maps API keys to work
S
Sebastien

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.


K
Khayer

Use below one,

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));


This is for Google Maps API v2
You need to provide a more thought out solution. And I believe this is for Google Maps v2.