Google Maps V3:更新标记

时间:2013-12-10 15:42:33

标签: javascript ajax google-maps google-maps-api-3 google-api

我在使用Google maps api v3时遇到了一些问题。我设法创建了一个地图,当用户拖动地图时会显示新标记。但是,它不会删除过去的标记。我已经阅读了很多教程和主题(特别是这一篇:Google Maps V3: Updating Markers Periodically)但没有成功。

这是我的主页:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Développez avec les API Google Maps</title>
<style type="text/css">
 html {
  height: 100%;
 }
 body {
  height: 100%;
  margin: 0px;
  padding: 0px;
 }
 #map_canvas {
  height: 100%;
 }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

function createXmlHttpRequest() {
    try {
        if (typeof ActiveXObject != 'undefined') {
            return new ActiveXObject('Microsoft.XMLHTTP');
        } else if (window["XMLHttpRequest"]) {
            return new XMLHttpRequest();
        }
    } catch (e) {
        changeStatus(e);
    }
    return null;
};

function downloadUrl(url, callback) {
    var status = -1;
    var request = createXmlHttpRequest();
    if (!request) {
        return false;
    }

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            try {
                status = request.status;
            } catch (e) {
            }
            if (status == 200) {
                callback(request.responseText, request.status);
                request.onreadystatechange = function() {};
            }
        }
    }
    request.open('GET', url, true);
    try {
        request.send(null);
    } catch (e) {
        changeStatus(e);
    }
};

function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') { 
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

 var map;

 function initialize() {
  var latlng = new google.maps.LatLng(46.7, 2.5);
  var myOptions = {
   zoom: 6,
   center: latlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

  downloadUrl("getPoi2.php", function(data) { 

   var xml = xmlParse(data);
   var markers = xml.documentElement.getElementsByTagName("marker");
   for (var i = 0; i < markers.length; i++) {
    createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
   }
  });

        /* Ici, on ajoute l'écouteur d'événement suite à un glisser / déposer  */ 
        google.maps.event.addListener(map, 'dragend', function() {
        var bds = map.getBounds();
        var South_Lat = bds.getSouthWest().lat();
        var South_Lng = bds.getSouthWest().lng();
        var North_Lat = bds.getNorthEast().lat();
        var North_Lng = bds.getNorthEast().lng();
            downloadUrl("getPoi.php?maxlat="+North_Lat+"&minlat="+South_Lat+"&minlong="+South_Lng+"&maxlong="+North_Lng, function(data) { 
            var xml = xmlParse(data);
            var markers = xml.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++) {
                createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
            }
            });
        });
 }

 function createMarker(lat, lng, titre){
  var latlng = new google.maps.LatLng(lat, lng);
  var marker = new google.maps.Marker({
   position: latlng,
   map: map,
   title: titre
  });

 }

</script>
</head>
<body onload="initialize()">
 <div id="map_canvas" style="width: 100%; height: 100%;"></div>

</body>
</html>

还有我的getPoin.php:

<?php
$user = "root";
$password = "";
$host = "localhost";
$bdd = "citiesinvaders";
mysql_connect($host,$user,$password);
mysql_select_db($bdd) or die("erreur de connexion à la base
de données");
$sql = "SELECT * FROM location order by city desc limit 1";
$res = mysql_query($sql) or die(mysql_error());
$dom = new DomDocument('1.0', 'utf-8');
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
while ($result = mysql_fetch_array($res)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("city", $result["city"]);
$newnode->setAttribute("lat", $result["latitude"]);
$newnode->setAttribute("lng", $result["longitude"]);
}
$xmlfile = $dom->saveXML();
echo $xmlfile;
?>

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

这是基于我对您的问题的理解...澄清...当地图移动时,标记被放置在旧标记上?又名他们在地图拖累上“加倍”?

创建一个数组来保存标记。

var markers = [];

然后,在'createMarker()'函数中将标记添加到数组中。另外,检查是否已创建标记,如果已创建,则不要重新创建。

function createMarker(lat, lng, titre) {
  for( marker in markers ) {
      var coord = marker.getgetPosition();
      if( coord.lat() == lat && coord.lng() == lng )
          return;
  }
  var latlng = new google.maps.LatLng(lat, lng);
  markers.push( new google.maps.Marker({
     position: latlng,
     map: map,
     title: titre
  }));
}

答案 1 :(得分:0)

跟踪创建的google.maps.Marker对象,在创建新对象之前将其删除。

var map;
var gmarkers = [];


/* Ici, on ajoute l'écouteur d'événement suite à un glisser / déposer  */ 
google.maps.event.addListener(map, 'dragend', function() {
  var bds = map.getBounds();
  var South_Lat = bds.getSouthWest().lat();
  var South_Lng = bds.getSouthWest().lng();
  var North_Lat = bds.getNorthEast().lat();
  var North_Lng = bds.getNorthEast().lng();
  downloadUrl("getPoi.php?maxlat="+North_Lat+"&minlat="+South_Lat+"&minlong="+South_Lng+"&maxlong="+North_Lng, function(data) { 
    var xml = xmlParse(data);
    var markers = xml.documentElement.getElementsByTagName("marker");

    // hide and delete the existing markers
    for (var i=0; i<gmarkers.length; i++) {
      gmarkers[i].setMap(null);
    }
    gmarkers = [];

    for (var i = 0; i < markers.length; i++) {
      createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
    }
  });
});

function createMarker(lat, lng, titre){
  var latlng = new google.maps.LatLng(lat, lng);
  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: titre
  });
  // keep a reference to created markers so you can remove them 
  gmarkers.push(marker);
}