如何更改Google地图位置,以便在选择框更改时,另一个纬度和长坐标位于Google地图的中心。地图和标记已成功加载。唯一要改变的是让我们说从已经加载的地图滚动到从选择框中选择的正确的城市。不应改变标记的坐标。
<select>
<option value="1" selected>NYC</option>
<option value="2">Chicago</option>
<option value="3">Boston</option>
</select>
<div class="map-container">
<div id="map"></div><!--the google map is loaded already-->
</div>
答案 0 :(得分:2)
如果您拥有下拉城市位置的坐标,请使用它们。如果没有,您可以使用地理编码器(如果您提供它识别的名称):
代码段
function initialize() {
var map = new google.maps.Map(document.getElementById("map"));
var geocoder = new google.maps.Geocoder();
$("#dropdown").change(function() {
address = $("#dropdown :selected")[0].text;
geocodeAddress(address, geocoder, map);
});
var address = $("#dropdown :selected")[0].text;
geocodeAddress(address, geocoder, map);
}
google.maps.event.addDomListener(window, "load", initialize);
function geocodeAddress(address, geocoder, resultsMap) {
document.getElementById('info').innerHTML = address;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.fitBounds(results[0].geometry.viewport);
document.getElementById('info').innerHTML += "<br>" + results[0].geometry.location.toUrlValue(6);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
&#13;
html,
body,
#map,
.map-container {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
<option value="1" selected>New York City</option>
<option value="2">Chicago</option>
<option value="3">Boston</option>
<option value="4">Palo Alto</option>
<option value="5">Seattle</option>
</select>
<div id="info"></div>
<div class="map-container">
<div id="map"></div>
<!--the google map is loaded already-->
</div>
&#13;