14

Hi all I need to be able to center the polyline in the center of the map

Only the necessery part of the code...

success: function(data) {//callback to be executed when the response has been received

    data = JSON.parse(data);
    for (var i=0;i<data.length;i++) {
        flightPlanCoordinates[i] = new google.maps.LatLng(data[i].x,data[i].y);
    }
    map = new google.maps.Map(document.getElementById("map_find"),
    mapOptions);
    flightPath = new google.maps.Polyline({
            path: flightPlanCoordinates,
            strokeColor: "#8a2be2",
            strokeOpacity: 1.0,
            strokeWeight: 3
    });

    flightPath.setMap(map);
    map.setZoom(5);
    map.setCenter(flightPlanCoordinates);
}

This is not doing what I need..My map is not centered and not zoomed, how to achieve this?

Teneff
  • 30,564
  • 13
  • 72
  • 103
user123_456
  • 5,635
  • 26
  • 84
  • 140

1 Answers1

37

You can use this function, calling it with the polyline as parameter:

function zoomToObject(obj){
    var bounds = new google.maps.LatLngBounds();
    var points = obj.getPath().getArray();
    for (var n = 0; n < points.length ; n++){
        bounds.extend(points[n]);
    }
    map.fitBounds(bounds);
}

Call it:

flightPath.setMap(map);
zoomToObject(flightPath);

Just make sure that your map object is a global variable.

Marcelo
  • 9,387
  • 3
  • 35
  • 40
  • I need to call it before this line `flightPath.setMap(map);` ? – user123_456 Oct 23 '12 at 09:49
  • I think that your code is working, but know my map is not initialized in the whole div...it is like in the 1/6 of the entire div when I call this function. Any idea? – user123_456 Oct 23 '12 at 09:57
  • It's probably best if you post a new question with full code. Does your map
    have a size? (both width and height)?
    – Marcelo Oct 23 '12 at 10:03
  • I have post a new question, check it out: http://stackoverflow.com/questions/13032245/google-polyline-is-not-in-the-center-and-not-zoomed – user123_456 Oct 23 '12 at 14:05