所以我在一个地理定位项目( asp.net MVC4 )中工作,我在我的数据库中有很多位置,我想在我的地图中显示它,我的问题是脚本只显示第一个这是我的剧本:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++)
{
var place = locations;
for (var i = 0; i < place.length; i++)
{
var points = new google.maps.LatLng(place[i][1], place[i][2]);
checkpoints.push(points);
}
var check = checkpoints[0];
var index = 0;
for (var j = 0; j < checkpoints.length; j++)
{
check = checkpoints[j];
index = j;
var myLatLng = new google.maps.LatLng(place[index][1], place[index][2]);
var marker = new google.maps.Marker
(
{
position: myLatLng,
map: map,
title: place[index][0],
zIndex: place[index][3]
}
);
}
}
return marker;
}
所以,如果有人有任何解决方案或想法,我将非常感激。
谢谢大家@david @ Beetroot-Beetroot @razzak我的脚本现在运行正常,这是我的新脚本:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i in locations) {
var points = new google.maps.LatLng(locations[i][1], locations[i][2]);
checkpoints.push(points);
var marker = new google.maps.Marker({
map: map,
position: points,
title: locations[i][0],
zindex: locations[i][4]
});
}
}
更新 我的脚本工作正常,但我的事件中有一个小问题,当我在标记上显示它应该显示他的标题,但它只显示我最后一个标记的标题:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i in locations) {
var points = new google.maps.LatLng(locations[i][1], locations[i][2]);
checkpoints.push(points);
var marker = new google.maps.Marker({
map: map,
position: points,
title: locations[i][0],
zindex: locations[i][4],
});
//this is my event
google.maps.event.addListener(marker, 'dblclick', function () {
alert("I am marker " + marker.title);
});
}
}
答案 0 :(得分:1)
我简化了你的代码
function setMarkers(locations) {
for(var i in locations) {
var points = new google.maps.LatLng(locations[i][1].lat,locations[i][2].lng);
checkpoints.push(points);
var marker = new google.maps.Marker({
map:map,
position: points,
icon: 'myicon.png',//
title: locations[i][0],
zindex: locations[i][4]
});
}
}
答案 1 :(得分:0)
试试这个:
function setMarkers(map, locations) {
for(var i=0; i<locations.length; i++) {
var loc = locations[i];
loc[4] = new google.maps.Marker({
position: new google.maps.LatLng(loc[1], loc[2]),
map: map,
title: loc[0],
zIndex: loc[3]
});
}
}
然后地图应该显示标记,locations
数组的每个成员都应该使用对其标记的引用进行扩充,作为元素[4]。
答案 2 :(得分:0)
主循环内的两个循环导致问题,它们是不必要的并且可以避免。在循环结束时返回标记也只返回最后一个,你也可以删除它:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i=0; i<locations.length; i++)
{
var place = locations[i],
myLatLng = new google.maps.LatLng(place[1], place[2]),
marker = new google.maps.Marker
(
{
position: myLatLng,
map: map,
title: place[0],
zIndex: place[3]
}
);
checkpoints.push({"point": myLatLng, "marker": marker});
}
}
检查点现在应该有每个地方LatLng
和marker
的数组。