gpt4 book ai didi

javascript - 谷歌地图引用标记监听器

转载 作者:行者123 更新时间:2023-11-30 15:39:36 24 4
gpt4 key购买 nike

我想在每个标记上添加一个监听器以放大它。

        var markers = [
['SIÈGE SOCIAL - CENTRE DE SOPHIA ANTIPOLIS', 43.582079, 7.051295],
['CENTRE DE PARIS', 48.788109, 2.319764],
['CENTRE DE RENNES', 48.152474, -1.698386],
['CENTRE DE NANTES', 47.215383, -1.53688],
['CENTRE DE GRENOBLE', 45.192752, 5.712405],
['CENTRE DE LYON', 45.768857, 4.864911],
['CENTRE DE AIX-EN-PROVENCE', 43.496824, 5.346391],
['CENTRE DE TOULOUSE', 43.56867, 1.387412]
];

for (i = 0; i < markers.length; i++) {

var marker = new google.maps.Marker({
position: {lat: markers[i][1], lng: markers[i][2]},
title: markers[i][0],
map: map
});


marker.addListener('click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());

});


}

但是无论点击什么标记, map 都会以最后一个标记位置为中心。

['CENTRE DE TOULOUSE', 43.56867, 1.387412]

最佳答案

最简单的解决方案是在标记点击事件监听器函数中使用 this,它引用被点击的标记。

marker.addListener('click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
});

proof of concept fiddle

代码片段:

var geocoder;
var map;

function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position: {
lat: markers[i][1],
lng: markers[i][2]
},
title: markers[i][0],
map: map
});
bounds.extend(marker.getPosition());
marker.addListener('click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
var markers = [
['SIÈGE SOCIAL - CENTRE DE SOPHIA ANTIPOLIS', 43.582079, 7.051295],
['CENTRE DE PARIS', 48.788109, 2.319764],
['CENTRE DE RENNES', 48.152474, -1.698386],
['CENTRE DE NANTES', 47.215383, -1.53688],
['CENTRE DE GRENOBLE', 45.192752, 5.712405],
['CENTRE DE LYON', 45.768857, 4.864911],
['CENTRE DE AIX-EN-PROVENCE', 43.496824, 5.346391],
['CENTRE DE TOULOUSE', 43.56867, 1.387412]
];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

关于javascript - 谷歌地图引用标记监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41022869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com