javascript - 如何通过单击按钮更改 Google map 中心

标签 javascript jquery html google-maps google-maps-api-3

我正在使用 Google Map API v3 和 jQuery 1.11.0。

我在以下 div 中有一个 Google map :

<div id="googleMap" class="map_div"></div>

ma​​p.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/

相关文章:

javascript - Bootstrap 固定边栏示例

javascript - FusionCharts-在 Column2D 图表中单击时更改条形的颜色

javascript - 文件太大,即使 php.ini 文件已更改,也无法上传到服务器

javascript - 如何只获取 <li> 文本而不从 li 中的其他元素获取文本

jquery - 使用 div 自己的无限滚动

html - HTML5 网络应用程序可以访问 Windows 7 平板电脑上的相机吗

javascript - iOS:WKWebView 中的 Javascript 代码在从照片库中选择照片并上传到服务器之前出现 “query cancelled” 错误

javascript - 搜索 Sencha TreePicker

javascript - 如何将自定义工具提示添加到 angular-nvd3 多条形图?

javascript - 如何设置我的标题动画以在加载时从左侧水平滑入页面 View ?