我有一个公交API,我在谷歌地图上展示轻轨车辆。我能够显示标记,但当我鼠标悬停以显示信息窗口时,所有标记都会显示相同的纬度/经度。就像所有车辆只显示一组车辆的一组坐标一样。我觉得我在这里容错了。
<script>
var map;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.5231, lng: -122.6765},
zoom: 11
});
{% for vehicle in vehicles %}
var marker = new google.maps.Marker({
position: {lat: {{ vehicle.latitude }}, lng: {{ vehicle.longitude }}},
map: map
});
infowindow = new google.maps.InfoWindow({
content: "Position: "+String({{ vehicle.latitude }})+String({{ vehicle.longitude}})
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
{% endfor %}
}
</script>
答案 0 :(得分:0)
你只创建一个infowindow(你用新的覆盖它,让它包含最后一个标记的信息)。您可以使用函数关闭来修复它,如Google Maps JS API v3 - Simple Multiple Marker Example的答案所示。
另一种选择是将信息窗或其内容存储在标记的自定义成员中。
var marker = new google.maps.Marker({
position: {lat: {{ vehicle.latitude }}, lng: {{ vehicle.longitude }}},
map: map,
content: "Position: "+String({{ vehicle.latitude }})+String({{ vehicle.longitude}})
});
marker.addListener('mouseover', function() {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
代码段
var map;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 42,
lng: -72
},
zoom: 10
});
infowindow = new google.maps.InfoWindow({});
// {% for vehicle in vehicles %}
var marker = new google.maps.Marker({
position: {
lat: 42,
lng: -72
},
map: map,
content: "Position: " + 42 + "," + -72
});
marker.addListener('mouseover', function() {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
var marker = new google.maps.Marker({
position: {
lat: 42.1,
lng: -72.1
},
map: map,
content: "Position: " + 42.1 + "," + -72.1
});
marker.addListener('mouseover', function() {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
google.maps.event.addDomListener(window, "load", initMap);
&#13;
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;