标记新的位置已创建,但旧的也显示在ajax谷歌地图

时间:2016-02-22 07:13:45

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

您好我试图从ajax获取标记latlon,我每秒获取ajax数据并且还能够在半径内创建标记,现在我正面临更新标记位置的问题,就像创建当前新标记一样和老一个也表现出来。请帮助更新我从ajax获取的标记并删除额外的。

    var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;

jQuery('#search').click(function() {
    var address = jQuery('#address').val() || 'India';
    if (map === null)
        initializeMap();
    searchAddress(address);
});

function initializeMap() {
    var mapOptions = {
        zoom: minZoomLevel,
        draggable: true,
        disableDefaultUI: true,
        scrollwheel: true,
        disableDoubleClickZoom: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);     
    if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(function (position) {
             initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
             map.setCenter(initialLocation);
             // Limit the zoom level
 google.maps.event.addListener(map, 'zoom_changed', function () {
     if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
 });
         });
     }
    google.maps.event.addListener(map, "idle", function(event) {
        searchStoresBounds();
    });
    geocoder = new google.maps.Geocoder();
    infoWindow = new google.maps.InfoWindow();
}


function searchAddress(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            var latlng = results[0].geometry.location;
            map.setCenter(latlng);
                         // Limit the zoom level
 google.maps.event.addListener(map, 'zoom_changed', function () {
     if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
 });
            searchStoresBounds();

        } else {
            alert('Geocode was failed: ' + status);
        }
    });
}


setInterval(function searchStoresBounds() {
    var bounds = map.getCenter().toUrlValue();
    var url = './store.php';
    var parameter = { bounds: bounds };
    jQuery.ajax({
        url: url,
        data: parameter,
        dataType: 'json',
        success: showStores
    });
}, 1000);


function showStores(data, status, xhr) {
    if (data['status'] != 'OK')
        return;

    var id;

    // add markers for new stores
    for (id in data['data']) {
        if (markers[id] === undefined)
            createMarker(id, data['data'][id]);
    }

    var b = map.getBounds();
    // remove markers out of the bounds
    for (id in markers) {
        if (! b.contains(markers[id].getPosition())) {
            markers[id].setMap(null);
            delete markers[id];
        }else{createMarker(id, data['data'][id]);}
    }
}

function createMarker(id, store) {

    var latlng = new google.maps.LatLng(
                parseFloat(store['lat']),
                parseFloat(store['lng'])
            );
    var html = "<b>" + store['address'] + "</b>";
    var x = store['distance'];

        var y = 1000;
        var z = x * y;
    var m = 85;
    var t = z / m;
    document.getElementById("demo").innerHTML = Math.ceil(t);
       var headm = store['bearing'];
       var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-

2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z 

M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z 

M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z 

M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
    path: car,
    scale: .7,
    strokeColor: 'White',
    strokeWeight: .4,
    fillOpacity: 1,
    fillColor: '#333333',
    offset: '5%',
    rotation: parseInt(headm),
    // rotation: parseInt(heading[i]),
    anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
       var marker = new google.maps.Marker({
            map: map,
            position: latlng,
            icon: icon,

        });
    google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
        });
    markers[id] = marker;
}

1 个答案:

答案 0 :(得分:1)

由于这部​​分

,您正面临着这个问题
var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: icon,

    });

每次从ajax获取数据时,它都会创建一个新标记。

在js页面顶部添加以下声明

var marker;

并将标记创建更改为以下

if(marker)
{
   marker.setMap(null);
}
marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: icon,
   });

在创建新标记之前,将从地图中删除上一个标记。需要if(标记)部分来检查是否已创建标记实例,因为第一次运行该标记实例时将没有标记,并且在尝试删除标记时会出现错误。

修改1:

由于您有多个标记,因此需要存储一系列标记并在地图上添加新标记之前将其删除

在页面顶部,您需要声明

var markerArray = new Array();

在添加标记之前,您需要清除以前的标记

for(var i = 0; i<markerArray.length; i++)
{
   markerArray[i].setMap(null);
}
markerArray = new Array()

之后将是您当前的代码

var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: icon,
   });

markerArray.push(marker);

您需要将标记添加到markerArray,以便下次执行代码时可以清除它。