[英]How to change to the center of a marker on a HTML button click
我正在使用谷歌地圖 API,並希望在單擊 (html) 按鈕時將地圖中心設置為特定位置。
我嘗試添加一個名為 newLocation 的函數,它接受兩個參數作為經度和緯度。 然后一個不同的函數連接到 ID 為“TestButton”的按鈕。
HTML 按鈕
<button class="item-button"><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span></button>
<button class="item-button" id="TestButton"><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span></button>
</div>
CSS
#map {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
創建地圖和設置
var map;
function initMap() {
//Set center map
var CenterLoc = { lat: 51.34, lng: 5.53 };
//Set map settings
map = new google.maps.Map(document.getElementById('map'),
{
center: CenterLoc,
disableDefaultUI: true,
zoom: 3,
});
創建功能和設置中心
//Center function
function newLocation(newLat, newLng) {
map.setCenter({
lat: newLat,
lng: newLng
});
}
google.maps.event.addDomListener(window, 'load', initMap);
//Setting location center
$(document).ready(function () {
$("TestButton").on('click', function () {
newLocation(48.1293954, 11.556663);
});
});
<script src="http://code.jquery.com/jquery.min.js"></script>
這些是我認為與此問題相關的所有代碼部分。 然而,整個代碼在這里: https : //pastebin.com/dzFYYtDH
我在瀏覽器控制台中沒有收到任何錯誤。 但是當我按下按鈕時什么也沒有發生。
在 JQuery 中,要使用其 id 屬性選擇或查找唯一的 HTML 元素,您需要使用#id
選擇器。
在您的情況下,請使用以下內容:
$(document).ready(function () {
$("#TestButton").on('click', function () {
newLocation(48.1293954, 11.556663);
});
});
這是jsfiddle 中的一個工作示例。 有關 JQuery #id 選擇器的更多信息,請點擊此處。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.