From An Array Of Coordinates, How Could I Decide Which To Center The Map On?
Assuming I am working with the following JSON of locations: var beaches = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronull
Solution 1:
The Google Maps API v3 contains a method for displaying a set of markers:
fitBounds(bounds:LatLngBounds) - None - Sets the viewport to contain the given bounds.
Add all your markers to a google.maps.LatLngBounds object, then call that method on your map object. Like this:
function initialize_map(places, zoom) {
var bounds = new google.maps.LatLngBounds(); // empty bounds object// use first coordinates in the json to initiate the mapvar place_lat_lng = new google.maps.LatLng(places[0][1],places[0][2]);
var mapOptions = {
zoom: zoom,
center: place_lat_lng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
varmap = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var marker, i;
// loop through all the places to get markersfor (var i=0;i<places.length;i++)
{
var place = places[i];
marker = new google.maps.Marker({
position: new google.maps.LatLng(place[1], place[2]),
map: map,
animation: google.maps.Animation.DROP
});
// add the marker
marker.setMap(map);
bounds.extend(marker.getPosition()); // add the marker to the bounds
}
map.fitBounds(bounds); // show all the markers.
}
Solution 2:
Here's a quick way to add the markers to a LatLngBounds and grab the center of the box. This will at the very least show you all the markers you've got. The rectangle and 'C' marker are to show you what the bounding box and center look like.
var bounds = new google.maps.LatLngBounds();
for (x in beaches) {
var data = beaches[x];
var lat = beaches[x][1];
var lng = beaches[x][2]
var latLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
map: map,
position: latLng
});
markers.push(marker);
bounds.extend(latLng);
}
map.fitBounds(bounds)
new google.maps.Rectangle({
bounds: bounds,
fillColor: '#000000',
map: map
})
var centerBounds = new google.maps.Marker({
map: map,
position: bounds.getCenter(),
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=C|FF0000|000000'
});
Post a Comment for "From An Array Of Coordinates, How Could I Decide Which To Center The Map On?"