Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps: API 3, how to set polyline in the center

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?

like image 808
user123_456 Avatar asked Oct 23 '12 09:10

user123_456


People also ask

How do you center in Google Maps?

Please go to your map and drag and drop your map to the position you wish. You can also zoom in your map a little bit with mouse wheel or zoom cotrols on the bottom right corner of the map. Please remember to save your map after any changes. Hope that helps.

What does fitBounds do in Google Maps?

Sets the viewport to contain the given bounds. Note: When the map is set to display: none , the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden , thereby ensuring the map div has an actual size.

How do I calculate the area of a polygon in Google Maps?

Right-click on the map at your starting point and choose the Measure distance option. Add points around the location's boundary. Once you close the shape by clicking on the starting point, the Google Maps area calculator will automatically process the area of your shape.


1 Answers

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.

like image 58
Marcelo Avatar answered Sep 22 '22 05:09

Marcelo