Google Maps API - 按关键字(城市名称)定位/中心

2024-06-25

在我的网络应用程序中,我使用 gmap javascript API (https://developers.google.com/maps/documentation/javascript/ https://developers.google.com/maps/documentation/javascript/)。我在函数中使用下面的代码,在用户按下按钮后定位/居中 gmap。

var position = new google.maps.LatLng(lat, lng);
map.setCenter(position);

此代码使用纬度和经度。我想根据给定的关键字定位/居中 gmap,而不是纬度和经度。例如,如果输入是“巴黎”,如何定位/居中 gmap?


您可以使用 Maps JavaScript API 的地理编码器服务来解析您的输入(例如巴黎)以协调地图并将其居中。

看看下面的代码示例

var map;
function initMap() {
  var geocoder = new google.maps.Geocoder();

  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 0, lng: 0},
    zoom: 8
  });

  geocoder.geocode({'address': "Paris"}, function(results, status) {
    if (status === 'OK') {
      map.setCenter(results[0].geometry.location);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });


}
#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&callback=initMap" async defer></script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Maps API - 按关键字(城市名称)定位/中心 的相关文章

随机推荐