【问题标题】:Google Maps API - position/center by keyword (city name)Google Maps API - 按关键字定位/中心(城市名称)
【发布时间】:2017-12-21 09:57:21
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript jquery html google-maps google-maps-api-3


【解决方案1】:

您可以使用 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>

【讨论】:

  • 不起作用。即使我在嵌入 JS 脚本时提供了 API_KEY,也总是获得 REQUEST_DENIED 状态。
  • @Radek Strugalski 仔细检查您的项目。您是否启用了 Maps JavaScript API 和 Geocoding API?您是否为 API 密钥启用了计费功能?
  • 是的,我昨天发现要使用 Geocode API,您需要启用它并为此支付额外费用。 (1000 次左右通话 5 美元)。
猜你喜欢
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 2013-04-14
相关资源
最近更新 更多