我正在使用 Google Map API v3 和 jQuery 1.11.0。
我在以下 div 中有一个 Google map :
<div id="googleMap" class="map_div"></div>
map.js 在 html 文件之外,它是链接的。
现在我在 html 的另一部分(外部 map )有一个按钮,如下所示:
<button id="3">Change center</button>
现在我想添加一个点击事件,它将 map 的中心更改为新的纬度和经度。
所以,我在 HTML 中有这样的 JavaScript:
<script>
$(document).ready(function()
{
$("#3").click(function(){
var center = new google.maps.LatLng(10.23,123.45);
map.panTo(center);
});
});
</script>
谁能帮帮我?在此先感谢您的帮助。
最佳答案
这是你的问题的代码:
var map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(48.1293954,12.556663),//Setting Initial Position
zoom: 10
});
}
function newLocation(newLat,newLng)
{
map.setCenter({
lat : newLat,
lng : newLng
});
}
google.maps.event.addDomListener(window, 'load', initialize);
//Setting Location with jQuery
$(document).ready(function ()
{
$("#1").on('click', function ()
{
newLocation(48.1293954,11.556663);
});
$("#2").on('click', function ()
{
newLocation(40.7033127,-73.979681);
});
$("#3").on('click', function ()
{
newLocation(55.749792,37.632495);
});
});
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<button id="1" style="padding:10px; cursor:pointer;">Munich</button>
<button id="2" style="padding:10px;cursor:pointer;">New York</button>
<button id="3" style="padding:10px;cursor:pointer;">Moscow</button>
<br>
<br>
<div style="height:100%;" id="map-canvas"></div>
Live demo is here如果你需要更多:).
关于javascript - 如何通过单击按钮更改 Google map 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28499141/