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

标签 javascript jquery html 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);

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

最佳答案

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

看看下面的代码示例

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>

关于javascript - Google Maps API - 按关键字定位/中心(城市名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134477/

相关文章:

javascript - Angular 矩没有显示任何东西

javascript - Reactjs和material-ui库导入报错

html - 简单样式表在 FireFox 中不起作用(字体大小)

html - @font-face 字体在本地工作正常但是当推送到服务器时它只是显示为默认 HTML 字体

c# - 如何将值从 ASP.NET 控件获取到 Web 表单中的 javascript

javascript - 按子元素的数据 ID 对 li 进行排序 - jQuery

javascript - laravel 和数据表无法集成

javascript - 任何对键控对象的使用都应该包装在 React.addons.createFragment(object) 中

javascript - 通过发送选项选择。 jQuery

javascript - 将 jScrollPane JQuery 插件与 RequireJS 一起使用