获取在Google地图中点击的城市名称

问题描述 投票:-1回答:1

在JavaScript中使用GoogleMaps API,我试图在地图上点击城市的名称(和位置)。

首先,我虽然可以使用这个PointOfInterest Event中解释的example功能,但是城市似乎没有提供所需的placeId

其次,我尝试使用here描述的反向地理编码机制来获取位置的完整地址,并从此处提取城市名称(地点):

this.map.addListener('click', (event) => {
    this.geocoder.geocode({
        location: event.latLng,
    }, (results, status) => {
        if(status === 'OK')
        {
            if(results && results.length)
            {
                const addressResult = results[0];

                if(addressResult.address_components)
                {
                    addressResult.address_components.forEach((component) => {
                        if(component.types.includes('locality'))
                        {
                            console.log(component.long_name);
                        }
                    });
                }
            }
        }
    });
});

这个方法给了我很好的结果,但它也显示了一些问题:

  • 尽管将地图区域设置为en,但我仍然得到城市的名称,因为它出现在地理编码器返回的地址中。例如,我得到日内瓦(法语名称为日内瓦)而不是日内瓦,我得到了慕尼黑(慕尼黑的德国名字)而不是慕尼黑
  • 点击一个城市,如果点击的位置属于另一个地方,我有时会得到另一个城市。

任何建议点击城市的名称将非常感激。

javascript google-maps google-maps-api-3 location city
1个回答
1
投票

执行反向地理编码时,服务将返回不同类型的结果。第一个通常是最近的街道地址,之后您将获得其他结果,如邻居,POI,地点,行政区域和国家。

在您的代码中,您可以选择第一个结果(最近的街道地址)来获取城市的名称。在这种情况下,您应该知道地理编码服务以本地语言而不是您在Maps JavaScript API初始化中指定的语言返回街道和地点的名称。您可以在此博客文章中阅读有关此政策的信息:

https://maps-apis.googleblog.com/2014/11/localization-of-street-addresses-in.html

对于政治实体,此规则未应用,因此您将获得在JavaScript API初始化中指定的语言类型的地点或管理区域的项目。

为了获得英语中的本地名称,您应该按类型过滤结果,并读取其地址组件以获取位置名称。

我稍微修改了你的代码以获得英语的地方,注意变量filtered_array做了一个技巧。

var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 47.295077, lng: 9.211874},
      zoom: 8
    });

    var geocoder = new google.maps.Geocoder();

    map.addListener('click', (event) => {
      geocoder.geocode({
        location: event.latLng,
      }, (results, status) => {
        if(status === 'OK') {
            if(results && results.length) {
                var filtered_array = results.filter(result => result.types.includes("locality")); 
                var addressResult = filtered_array.length ? filtered_array[0]: results[0];

                if(addressResult.address_components) {
                    addressResult.address_components.forEach((component) => {
                        if(component.types.includes('locality')) {
                            console.log(component.long_name);
                        }
                    });
                }
            }
        }
    });
  });
} 
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&language=en&callback=initMap"
    async defer></script>

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.