我有一个关于在各个国家远足的页面。我正在尝试为每个国家/地区制作一个这样的页面,但不确定如何自动将谷歌地图围绕一个国家/地区居中,并让它根据国家/地区的大小调整焦点。
这是我的问题页面:
http://www.comehike.com/outdoors/country.php?country_id=6&country_name=Belarus
http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United%20States
您看到居中和焦点大小是如何静态的吗?那是因为我目前使用此代码将 map 居中:
function initialize( )
{
var myLatlng = new google.maps.LatLng(37.775, -122.4183333);
var myOptions =
{
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
但这只是因为我不确定如何按国家名称进行操作,并自动调整大小。如何通过将国家/地区名称传递给初始化函数来完成这一切?
谢谢!
最佳答案
您可以使用 Geocoding service 将国家名称转换为坐标. Google 提供的示例将 map 居中,但不会对其进行缩放。要缩放它,您应该使用 map.fitBounds() 方法,使用地理编码器返回的 LatLngBounds 对象。
这是一个示例代码:
var myLatlng = new google.maps.LatLng(37.775, -122.4183333);
var myOptions =
{
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Belarus";
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.bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
关于google-maps - 如果您只有国家/地区名称,如何将谷歌地图围绕一个国家/地区居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6086326/