How to get Google Maps API to set the correct zoom level for a country?
Is there a was of automatically setting the zoom level based on the size of the country that the map has been centered on?
maps.google.com does exactly what I need, so, for example, if I search for Russia I get a zoom level such that Russia just fits on screen, and when I search for Cuba I get a higher zoom level so that Cuba just fits.
Is there some way of giving the Maps Api a country location and getting an appropriate zoom level.
If not, I guess that I would have to manually (ugh!) create my own table for this information. Or is this information freely available somewhere?
For API v3 check the answer below.
You can use the Google Maps Client-side Geocoder to get the bounding box of the country, as in the following example:
// API version 2
var geocoder = new GClientGeocoder();
geocoder.getLocations("Russia", function (locations) {
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
});
// API version 3
// ... set north, south, east and west ...
var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(south, west),
new google.maps.LatLng(north, east));
map.fitBounds(bounds);
The screenshots below show the results of the above technique when searching for Russia and Cuba:
对于V3这个代码为我工作:
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
}
});
如果你不使用谷歌地图API,只使用他们的地理编码,你可以使用这个公式:
var url = 'http://maps.google.com/maps/geo?q=YOUR_QUERY&output=json&oe=utf8&sensor=false&key=YOUR_KEYback=geoCodeDone';
jQuery.getScript(url);
function geoCodeDone(data)
{
if (data.Status.code == 200)
{
lng = data.Placemark[0].Point.coordinates[0];
lat = data.Placemark[0].Point.coordinates[1];
var east = data.Placemark[0].ExtendedData.LatLonBox.east;
var west = data.Placemark[0].ExtendedData.LatLonBox.west;
var zoom = 11 - Math.round(Math.log(Math.abs(west-east))/Math.log(2));
}
}
链接地址: http://www.djcxy.com/p/81588.html