2017-07-17 109 views
0

在我的web应用程序中,我使用gmap javascript API(https://developers.google.com/maps/documentation/javascript/)。我在一个函数中使用下面的代码来定位/中心gmap,一旦用户按下了一个按钮。Google Maps API - 按关键字(城市名称)排列/中心

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

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

+0

您可以使用[谷歌地图API的地理编码(https://developers.google.com/maps/documentation/geocoding /开始)获取所需城市的纬度/经度 –

回答

0

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

相关问题