Gen*_*nik 8 google-maps map geo google-maps-api-3
我有一个关于在各个国家徒步旅行的网页.我正在尝试为每个国家制作一个类似的页面,但不确定如何自动将谷歌地图置于一个国家/地区中心,并根据国家/地区的大小调整焦点.
这是我的问题页面:
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
你看到中心和焦点大小是如何静态的?那是因为我目前使用此代码来居中地图:
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);
}
Run Code Online (Sandbox Code Playgroud)
但这只是因为我不确定如何按国家名称来做,并自动调整大小.如何通过将国家/地区名称传递给初始化函数来完成所有操作?
谢谢!
Yur*_*ken 13
您可以使用地理编码服务将国家/地区名称转换为坐标.Google提供的示例以地图为中心,但不会对其进行缩放.要缩放它,您应该使用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);
}
});
Run Code Online (Sandbox Code Playgroud)