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

use*_*797 5 html javascript jquery google-maps google-maps-api-3

在我的网络应用程序中,我正在使用gmap javascript API(https://developers.google.com/maps/documentation/javascript/)。一旦用户按下按钮,我将在函数内部使用以下代码定位/居中放置gmap。

var position = new google.maps.LatLng(lat, lng);
map.setCenter(position);
Run Code Online (Sandbox Code Playgroud)

此代码使用纬度和经度。我想基于给定的关键字定位/居中放置gmap而不是纬度和经度。例如,如果输入为“ Paris”,如何定位/居中gmap?

xom*_*ena 5

您可以使用Maps JavaScript API的geocoder服务来解析您的输入(例如,巴黎)以协调和居中地图。

看看下面的代码示例

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


}
Run Code Online (Sandbox Code Playgroud)
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" async defer></script>
Run Code Online (Sandbox Code Playgroud)