【发布时间】:2014-09-26 08:27:43
【问题描述】:
结合使用 PHP 和 Javascript,我需要在 Google 地图上显示多个标记(至少 50 个)。
我浏览了链接: https://developers.google.com/maps/documentation/javascript/examples/map-latlng-literal 在第 15 行它说:
var marker = new google.maps.Marker({
// The below line is equivalent to writing:
// position: new google.maps.LatLng(-34.397, 150.644)
position: {lat: -34.397, lng: 150.644},
map: map
});
我打算做以下事情:
var markers = [<?php echo $locations ?>];
如果我这样做有错吗:
var markers = [{
position: {lat: 19.10427, lng: 72.92764},
map: map
},
{
position: {lat: 19.10432, lng: 72.92751},
map: map
}
];
然后我的意图是在 init 函数中调用 showMarkers()
我的js代码是:
src="https://maps.googleapis.com/maps/api/js?v=3.exp"
var map;
var markers = [{
position: {lat: 19.10427, lng: 72.92764},
map: map
},
{
position: {lat: 19.10432, lng: 72.92751},
map: map
}
];
function initialize() {
var haightAshbury = new google.maps.LatLng(19.10427,72.92764);
var mapOptions = {
zoom: 12,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
showMarkers();
}
// Add a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
这不起作用。在我的 Firefox 控制台中,我可以看到: "TypeError:markers[i].setMap 不是函数
这里是 jsFiddle 的链接: http://jsfiddle.net/P5tXh/4/
我做错了什么?
【问题讨论】:
-
您的“标记”数组是匿名对象数组,而不是 google.maps.Markers。该数组的元素没有 setMap 方法。
标签: javascript php arrays google-maps-api-3 google-maps-markers