How do I update the locations of multiple markers in google maps

有些话、适合烂在心里 提交于 2019-12-01 02:38:05

To change the location of a marker, call setPosition() on that marker:

marker.setPosition(new google.maps.LatLng(newLat,newLng);

To do this, you will need to save all your markers in an array. Perhaps something like this would work:

var myMarkers = new Array();
for (index in markers) {
    myMarker[ markers[index]['id'] ] = addMarker(map, markers[index]);
}

function addMarker(map, data) {
    //create the markers
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map,
        title: data.id,
        icon: image,
        shape: shape,
        shadow: shadow
    });

    //create the info windows
    var content = document.createElement("DIV");
    var title = document.createElement("DIV");
    title.innerHTML = data.id;
    content.appendChild(title);

    var infowindow = new google.maps.InfoWindow({
        content: content
    });

    // Open the infowindow on marker click
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
    return marker;    
}

Then, when the position of a marker needs to change, hopefully you know the bus ID and can just call:

myMarkers['Bus 47'].setPosition(new google.maps.LatLng(newLat,newLng);

I didn't test the above code so there may be small syntax errors or something, but it should give you the idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!