Javascript 更新了标记的位置,但上一个标记仍显示在google maps api中
我对GoogleMapsAPI非常陌生,我通过ajax更新了标记的坐标。我希望标记喜欢,移动,但它就像用新坐标生成一个新的标记,而前一个仍然存在。使用新坐标更新标记时,如何删除旧标记 maps.htmlJavascript 更新了标记的位置,但上一个标记仍显示在google maps api中,javascript,php,ajax,google-maps-api-3,Javascript,Php,Ajax,Google Maps Api 3,我对GoogleMapsAPI非常陌生,我通过ajax更新了标记的坐标。我希望标记喜欢,移动,但它就像用新坐标生成一个新的标记,而前一个仍然存在。使用新坐标更新标记时,如何删除旧标记 maps.html <!DOCTYPE html> <html> <head> <style> #map { width: 800px; height: 600px; } </style> <script
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 800px;
height: 600px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3&
amp;key=AIzaSyDh0-6mPaP9RezyUZkrv2uqX8BGh3nzFCM"></script>
<script src="maps.js"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
#地图{
宽度:800px;
高度:600px;
}
maps.js
function initialize() {
// Create a map object and specify the DOM element for display.
var mapCanvas = document.getElementById('map');
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
setInterval(function(){
requestLatLng('getlatlng.php', function(data){
var data = JSON.parse(data.responseText);
displayMarker(data);
//alert(parseFloat(data.latitude) + " " + parseFloat(data.longitude))
console.log(parseFloat(data.latitude) + " " + parseFloat(data.longitude));
map.setCenter(new google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude)));
});
}, 3000);
var gmarkers = [];
var marker;
function displayMarker(data){
var myLatLng = {lat: parseFloat(data.latitude), lng: parseFloat(data.longitude)};
var title = data.name + ", " + data.country;
marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: title
});
if(gmarkers.length < 1){
gmarkers.push(marker);
}
console.log(gmarkers.length);
//console.log("x: " + gmarkers[0].tg.xa.x + "\ny: "+ gmarkers[0].tg.xa.y)
}
}
function requestLatLng(url, callback){
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
google.maps.event.addDomListener(window, 'load', initialize);
函数初始化(){
//创建贴图对象并指定要显示的DOM元素。
var mapCanvas=document.getElementById('map');
变量映射选项={
缩放:8,
mapTypeId:google.maps.mapTypeId.ROADMAP
}
var map=new google.maps.map(mapCanvas,mapOptions)
setInterval(函数(){
requestLatLng('getlatlng.php',函数(数据){
var data=JSON.parse(data.responseText);
显示标记(数据);
//警报(parseFloat(数据.纬度)+“”+parseFloat(数据.经度))
log(parseFloat(data.latitude)+“”+parseFloat(data.longitude));
setCenter(新的google.maps.LatLng(parseFloat(数据.纬度),parseFloat(数据.经度));
});
}, 3000);
var gmarkers=[];
var标记;
功能显示标记(数据){
var myLatLng={lat:parseFloat(data.latitude),lng:parseFloat(data.longitude)};
var title=data.name+,“+data.country;
marker=新的google.maps.marker({
地图:地图,
职位:myLatLng,
标题:标题
});
如果(gmarkers.length<1){
G标记器。推(标记器);
}
控制台日志(gmarkers.length);
//console.log(“x:+gmarkers[0].tg.xa.x+”\ny:+gmarkers[0].tg.xa.y)
}
}
函数requestLatLng(url,回调){
var请求;
if(window.XMLHttpRequest){
请求=新的XMLHttpRequest();
}否则{
请求=新的ActiveXObject(“Microsoft.XMLHTTP”);
}
request.onreadystatechange=函数(){
if(request.readyState==4&&request.status==200){
回调(请求);
}
}
打开(“获取”,url,true);
request.send();
}
google.maps.event.addDomListener(窗口“加载”,初始化);
getlatlng.php
<?php
header('Content-type: application/json');
define('HOST', 'localhost'); // The host you want to connect to.
define('USER', 'root'); // The database username.
define('PASSWORD', ''); // The database password.
define('DATABASE', 'rummage'); // The database name.
global $conn;
// Check connection
try{
$conn = new PDO('mysql:host = '.HOST.';dbname='.DATABASE, USER, PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected successfully';
}catch (PDOException $e) {
echo "Connection failed " . $e->getMessage();
}
$id = 21;
$query = $conn->prepare("SELECT * FROM regions where id = ?");
$query->execute(array($id));
while($row = $query->fetch()){
$rows[] = $row;
}
foreach ($rows as $roww) {
echo json_encode($roww);
}
?>
这是我的getlatlng.php文件的json输出:
{“id”:“19”、“0”:“19”、“国家”:“AF”、“1”:“AF”、“代码”:“06”、“2”:“06”、“姓名”:“法拉”;“3”:“法拉”;“纬度”:“32.3754”、“4”:“32.3754”、“经度”:“62.1123”、“5”:“62.1123”、“城市”:“0”、“6”:“0”}我建议您检查这篇文章: 他使用html中的数组保存所有标记,然后更新它们。如果是一个新的,他只是创建它并把它放在列表中 编辑: 我就是这样做的:
//Used to remember markers
var markerStore = {};
//Time between marker refreshes
var INTERVAL = 250;
function getMarkers() {
$.ajax({
type: 'GET',
url: 'webresources/mobile/retrieve-position',
contentType: 'application/json',
dataType: "json", //linea fragril
beforeSend: function (xhr) {
// Set the CSRF Token in the header for security
var token = window.sessionStorage.accessToken;
if (token) {
xhr.setRequestHeader('userToken', token);
}
else {
xhr.abort();
}
},
success: function (res, textStatus, jqXHR) {
if (jqXHR.status !== 204) {
for (var i = 0; i < res.length; i++) {
if (markerStore.hasOwnProperty(res[i].username)) {
//Check if marker is still alive
if(res[i].alive){
Destroy the marker
markerStore[res[i].username].setMap(null);
}
else{
Change markers position reading the new marker information.
markerStore[res[i].username].setPosition(new google.maps.LatLng(res[i].lat, res[i].long));
}
}
else {
//If it doesnt exist, create a new one.
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + res[i].color);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(res[i].lat, res[i].long),
title: res[i].username,
icon: pinImage,
map: map
});
markerStore[res[i].username] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}
},
error: function () {
console.log("Error loading markers.");
}
});
}
//用于记住标记
var-markerStore={};
//标记刷新间隔时间
var区间=250;
函数getMarkers(){
$.ajax({
键入:“GET”,
url:'webresources/mobile/retrieve position',
contentType:'应用程序/json',
数据类型:“json”,//linea fragril
发送前:函数(xhr){
//为安全起见,在标头中设置CSRF令牌
var token=window.sessionStorage.accessToken;
如果(令牌){
setRequestHeader('userToken',token);
}
否则{
xhr.abort();
}
},
成功:函数(res、textStatus、jqXHR){
如果(jqXHR.status!==204){
对于(变量i=0;i
我建议您查看这篇文章:
他使用html中的数组保存所有标记,然后更新它们。如果是一个新的,他只是创建它并把它放在列表中
编辑:
我就是这样做的:
//Used to remember markers
var markerStore = {};
//Time between marker refreshes
var INTERVAL = 250;
function getMarkers() {
$.ajax({
type: 'GET',
url: 'webresources/mobile/retrieve-position',
contentType: 'application/json',
dataType: "json", //linea fragril
beforeSend: function (xhr) {
// Set the CSRF Token in the header for security
var token = window.sessionStorage.accessToken;
if (token) {
xhr.setRequestHeader('userToken', token);
}
else {
xhr.abort();
}
},
success: function (res, textStatus, jqXHR) {
if (jqXHR.status !== 204) {
for (var i = 0; i < res.length; i++) {
if (markerStore.hasOwnProperty(res[i].username)) {
//Check if marker is still alive
if(res[i].alive){
Destroy the marker
markerStore[res[i].username].setMap(null);
}
else{
Change markers position reading the new marker information.
markerStore[res[i].username].setPosition(new google.maps.LatLng(res[i].lat, res[i].long));
}
}
else {
//If it doesnt exist, create a new one.
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + res[i].color);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(res[i].lat, res[i].long),
title: res[i].username,
icon: pinImage,
map: map
});
markerStore[res[i].username] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}
},
error: function () {
console.log("Error loading markers.");
}
});
}
//用于记住标记
var-markerStore={};
//标记刷新间隔时间
var区间=250;
函数getMarkers(){
$.ajax({
键入:“GET”,
url:'webresources/mobile/retrieve position',
contentType:'应用程序/json',
数据类型:“json”,//linea fragril
发送前:函数(xhr){
//为安全起见,在标头中设置CSRF令牌
var token=window.sessionStorage.accessToken;
如果(令牌){
setRequestHeader('userToken',token);
}
否则{
xhr.abort();
}
},
成功:乐趣