我对Google Maps api很陌生,我通过ajax更新了标记的坐标。我希望标记器喜欢,移动,但它就像使用新坐标生成新坐标,而上一个坐标仍然存在。使用新坐标更新标记时,如何删除旧标记?
maps.html
<!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>
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);
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”,“名称“:” Farah \ r“,” 3“:” Farah \ r“,”纬度“:” 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.");
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句