Google Maps API - 按关键字排名/中心(城市名称) [英] Google Maps API - position/center by keyword (city name)

查看:95
本文介绍了Google Maps API - 按关键字排名/中心(城市名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my web application I am using the gmap javascript API (https://developers.google.com/maps/documentation/javascript/ ). I am using the code below inside a function to position/center the gmap once a user has pressed a button.

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

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

This code uses the latitude and longitude. Instead of the latitude and longitude I would like to position/center the gmap based on a given keyword. For example, how can I position/center the gmap if the input is 'Paris'?

推荐答案

您可以使用地理编码服务映射JavaScript API以解析您的输入(例如Paris)以协调和居中地图。

You can use geocoder service of Maps JavaScript API to resolve your input (e.g. Paris) to coordinate and center the 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>

这篇关于Google Maps API - 按关键字排名/中心(城市名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆