2017-07-17 74 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>

相關問題