我正在尝试在Google地图上实时更新标记。我需要一个标记作为起始位置,然后随着位置的变化(用户移动),将绘制折线并且标记将显示当前位置。因此,对于每个用户,将有两个标记;一个显示起始位置,一个不断更新并显示当前位置。
我可以绘制线条和开始标记,但每次位置更改时都会使用此代码,而不是更新旧标记。我正在尝试使用setPosition();但它似乎没有用。有什么想法吗?
function initialize() {
var myLatlng = new google.maps.LatLng(39, -86);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var loc = {};
var mark = {};
var markers = {};
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var user_id = data[0];
var lati = data[1]; //get id
var longi = data[2]; //get name
var myLatlngt = new google.maps.LatLng(lati, longi);
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
//if (typeof markers[user_id] === 'undefined') {
//markers[user_id] = [];
//}
if (typeof mark[user_id] === 'undefined') {
mark[user_id] = myLatlngt;
}
loc[user_id].push(myLatlngt);
//markers[user_id].push(myLatlngt);
var marker1;
var x;
for (x in loc) {
var polyline = new google.maps.Polyline({
map: map,
path: loc[x],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
///location variables
var start_loc = loc[user_id];
var start_marker = start_loc[0]; //start location of given user
var current_loc = start_loc[start_loc.length -1]; //last known location of given user
//set the start marker
var marker = new google.maps.Marker({
position: start_marker,
title: user_id
});
marker.setMap(map);
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
else {
marker1 = new google.maps.Marker({
position: current_loc,
map: map
});
}
}
//console.log('location :::', x);
console.log('Marker: ', mark);
}
});
}, 1000);
});
});
}
答案 0 :(得分:1)
尝试在函数外声明 marker1 变量(var marker1;
),使其成为全局(范围)。在var markers = {};
之后应该这样做。如果这不起作用,请告诉我,我会更深入地了解它。