如何在只有国家名称的情况下将谷歌地图居中于该国家?

8

我有一个关于各个国家徒步旅行的页面。我想为每个国家制作这样的页面,但不确定如何自动将谷歌地图居中在一个国家周围,并根据国家大小调整焦点。

以下是我的问题页面:

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);
}

但这只是因为我不确定如何通过国家名称来调整大小。如何通过将国家名称传递到初始化函数来完成所有这些操作呢?

谢谢!

1个回答

14
您可以使用Geocoding服务将国家名称转换为坐标。谷歌提供的示例会将地图居中显示,但不会缩放地图。要进行缩放,您应该使用map.fitBounds() 方法,并使用geocoder返回的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);
    }
});

yuri,我仍然遇到一些JS错误... 这是一个例子页面:http://www.comehike.com/outdoors/country.php?country_id=1&country_name=United%20States - Genadinik
1
你出错了,因为这里:<body onload="initialize( United States );">,你应该加引号:<body onload="initialize('United States');"> - Yuri Stuken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接