jquery-ui-map fit bounds with a polyline?

2019-07-21 06:18发布

问题:

I'm working on a mobile app using jQuery Mobile. I also you the plugin "jquery-ui-map" to do my map (that helped alot with display issues using only GMap with jQM).

I'm able to add polyline on the map and it works just fine. But when I try to use the fitBounds method, it doesn't work. In fact, it zoom out alot. But not on my bounds.

Here is my code :

// Added some data, so you can understand the structure
// of variable "plan"
plan[0].lat_a = 45.4681;    plan[0].lng_a = -73.7414;
plan[0].lat_b = 45.6797;    plan[0].lng_b = -74.0386;
plan[1].lat_a = 45.6797;    plan[1].lng_a = -74.0386;
plan[1].lat_b = 48.7753;    plan[1].lng_b = -64.4786;

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

// Starting point
var LatLng = new google.maps.LatLng(plan[0].lat_a, plan[0].lng_a);
bounds.extend(LatLng);

// Building the polyline coords and bounds
for (var x=0; x<plan.length; x++) {
    polylinesCoords.push(new google.maps.LatLng(plan[x].lat_a, plan[x].lng_a), new google.maps.LatLng(plan[x].lat_b, plan[x].lng_b));
    LatLng = new google.maps.LatLng(plan[x].lat_b, plan[x].lng_b);
    bounds.extend(LatLng);
}

// Drawing polyline on map
$('#map_canvas').gmap('addShape', 'Polyline', {
    'path': polylinesCoords,
    'strokeColor': '#c00',
    'strokeThickness': 5
});

// «Focus» map on polyline with bounds
var map = $("#map_canvas").gmap("get", "map");
map.fitBounds(bounds);

Everything in this snippet seems to works fine, except for the very last line.

Any ideas ?

回答1:

You might've missed to center the map to any of your pin. I got your code working with this line of code

$('#map_canvas').gmap('option', 'center', (new google.maps.LatLng(plan[0].lat_a,plan[0].lng_a)));