0
我試圖在谷歌地圖上顯示幾個標記,並允許用戶在地圖上點擊標記時將標記居中。以標記爲中心,谷歌地圖API
但是,當用戶點擊任何標記時,地圖總是以我在代碼中創建的最後一個標記爲中心。
下面是完整的代碼我使用:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-34, 150),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var myLatLng = new google.maps.LatLng(34,-150);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title:'test' + 1
});
google.maps.event.addListener(marker, 'click', function(){map.setCenter(marker.getPosition());});
myLatLng = new google.maps.LatLng(20,-87);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title:'test' + 2
});
google.maps.event.addListener(marker, 'click', function(){map.setCenter(marker.getPosition());});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
花在這個一會,諮詢了谷歌地圖API的參考,但就是無法弄清楚,爲什麼它不工作。
任何見解讚賞 - 謝謝。
哦 - 我爲什麼要使用這種方法可以用在地方MY_API_KEY我的API代碼,當然:) – ploddingOn
的?您應該將緯度,經度和標題存儲在數組中,然後使用for循環來添加數據。否則,如果你想保持這種方式,重命名你的第二個變量marker2(或類似的東西),併爲marker2(或任何你命名它)添加一個事件偵聽器。 – andresf
我知道的老問題,但我在這裏發佈了相同的問題,然後設法自己解決它: http://stackoverflow.com/questions/15273835/google-maps-apis-clicking-marker-zooms-in-on-wrong -一 –