centering a google map based on marker lat long values
I'm plotting about 20 markers on a map, locations in a c开发者_如何学Pythonity. When I use getLatLng to find the city center it's always a little removed from the locations I'm plotting, which means the markers are usually located in a corner of my map instead of in the center.
is there a way to center the map on a location that is more central to my locations? I'm guessing I need some sort of "average" lat / long coordinate calculated from the 20 lat / long values I have available.
Is this possible?
Finding the center should be pretty easy. Just find the smallest and largest latitude and longitude coordinates in your group of 20.
The center will be [min_lat + (max_lat - min_lat)/2, min_long + (max_long - min_long)/2]
.
Something like:
var points = Array();
points.push(new GLatLng( xxx, yyy ));
...
min_lat = 90;
max_lat = -90;
min_long = 180;
max_long = -180;
for (p in points) {
if (p[0] < min_lat) {
min_lat = p[0];
}
if (p[0] > max_lat) {
max_lat = p[0];
}
if (p[1] < min_long) {
min_long = p[1];
}
if (p[1] > max_long) {
max_long = p[1];
}
}
center = new GLatLng(min_lat + (max_lat - min_lat) / 2,
min_long + (max_long - min_long) / 2];
map.setCenter(center, 10);
This code will probably have trouble if your points cross the longitude boundaries (±180°). It's also assuming that the points are located on a flat surface (rather than the surface of a sphere).
None of that should matter much if you're talking about coordinates within several hundred miles of each other in the US.
精彩评论