【问题标题】:How to center a google map around a country if you just have the country name如果您只有国家/地区名称,如何将谷歌地图围绕一个国家/地区居中
【发布时间】:2011-08-30 11:44:30
【问题描述】:

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

这是我的问题页面:

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

但这只是因为我不知道如何按国家名称进行操作,并自动调整大小。如何通过将国家/地区名称传递给初始化函数来完成这一切?

谢谢!

【问题讨论】:

    标签: google-maps map google-maps-api-3 geo


    【解决方案1】:

    您可以使用Geocoding service 将国家名称转换为坐标。 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);
        }
    });
    

    【讨论】:

    • yuri 我仍然遇到一些 JS 错误。这是一个示例页面:comehike.com/outdoors/…
    • 你有一个错误因为这个:<body onload="initialize( United States ); ">,你应该加上引号:<body onload="initialize('United States'); ">
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多