[英]Best approach to replicate Google Map's "re-center" when user interacts with the map in navigation mode using Leaflet JS
[英]Re-center Google Map after user submits location
我正在建立一個旅行計划程序,要求用戶輸入並提交他/他要去的城市的名稱。 我已經啟動了一個地圖,並將第一個位置設置為SF,但是我希望它根據用戶輸入的位置重新居中。
在發布之前,我遵循了這兩個參考(Google Maps API文檔除外),但兩個參考都不對我有用(我顯然缺少了一些東西)。 我得到map.setCenter()不是一個函數。
Google Maps API v3:如何將縮放級別和地圖中心設置為用戶提交的位置?
<h3>I'm traveling to: </h3>
<input class="inputBox" type="text" name="destination" id="destination" placeholder="e.g., Barcelona, Spain or China" maxlength="35">
<input type="submit" class="form" id="form">
<script type="text/javascript">
function initMap() {
var myLatlng = {lat: 37.7751, lng: -122.4194};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatlng
});
}
var button = document.querySelector("input.form");
var userSelectLat;
var userSelectLng;
//add an event listener which executes the callback function, geoLocation, when the Submit button is clicked
button.addEventListener("click", getLocation);
function getLocation(event) {
event.preventDefault()
//store city entered into a variable, put it in quotes, and add that to the geocode URL
var city = document.querySelector("input#destination.inputBox").value;
var cityInQuotes = "\"" + city + "\""
var geocodeURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+cityInQuotes+"AIzaSyBMEriLb8zqxFSVBWArM6n3MxonN5d-cLY";
//return JSON and
$.get(geocodeURL,printCoordinates)
}
function printCoordinates(results) {
if (results.status === "ZERO_RESULTS") {
alert("Location not found. Try searching for a city or more specific location.")
} else {
userSelectLat = results.results[0].geometry.location.lat;
userSelectLng = results.results[0].geometry.location.lng;
console.log('arrayresults = '+userSelectLat,userSelectLng);
}
//re-center map based on new location
var relocate = new google.maps.LatLng(userSelectLat, userSelectLng);
alert("setting the center to: " + relocate);
map.setCenter(relocate);
}
我只是想通了!
我在initMap函數外部定義了變量映射,然后在initMap函數內部的映射前面刪除了“ var”,因此它正在更新全局映射變量,而不是僅將其存儲在initMap內部。 做到了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.