Javascript 在 Google Maps API v3 中以国家/地区为中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4408397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:17:52  来源:igfitidea点击:

Center on a country by name in Google Maps API v3

javascriptgoogle-maps

提问by David

Would someone tell me how to center on a country by name on the Google Maps API v3? I know how to do it in v2, but need to do it in v3.

有人会告诉我如何在 Google Maps API v3 上按名称以国家/地区为中心吗?我知道如何在 v2 中执行此操作,但需要在 v3 中执行此操作。

回答by kzhen

You could use Geocoding to lookup the Lat/Lng of the country. Take a look at this samplefrom Google.

您可以使用地理编码来查找国家/地区的纬度/经度。看看来自 Google 的这个示例

Basically you need to do something like this:

基本上你需要做这样的事情:

var country = "Germany";
var geocoder;

geocoder.geocode( {'address' : country}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
    }
});

In your initialize function you'll need to set the value of the geocoder object, like this:

在您的初始化函数中,您需要设置地理编码器对象的值,如下所示:

geocoder = new google.maps.Geocoder();

You'd need to workout what an appropriate zoom level would be, and then set that after you have centered the map.

您需要练习适当的缩放级别,然后在将地图居中后进行设置。

回答by Ashish Gupta

This code working for me:

这段代码对我有用:

      let geocoder = new google.maps.Geocoder();
      let location = "England";
      geocoder.geocode({ 'address': location }, function(results, status){
          if (status == google.maps.GeocoderStatus.OK) {
              map.setCenter(results[0].geometry.location);
          } else {
              alert("Could not find location: " + location);
          }
      });

回答by Jose Vega

The only way I know how to do it would be by having a list of the countries and their respective Lat and Lng, with that information known you could use the following code.

我知道如何做到这一点的唯一方法是列出国家及其各自的 Lat 和 Lng,知道这些信息后,您可以使用以下代码。

var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
  zoom: 8,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

Out of curiosity, how would you do it in v2?

出于好奇,你会如何在 v2 中做到这一点?