且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Googlemaps-删除以前的标记

更新时间:2023-12-03 18:20:16

未经测试,但应做您想做的-请注意GMarkersetLatLng方法是在API版本2.88中引入的:

Untested, but should do what you want - note that the setLatLng method of GMarker was introduced in API version 2.88:

function initialize() {

    if (GBrowserIsCompatible()) {
        var marker;

        function showNewMarker(latlng) {
            marker = new GMarker(latlng);
            map.addOverlay(marker);
            showMarker = updateExistingMarker;
        }

        function updateExistingMarker(latlng) {
            marker.setLatLng(latlng);
        }

        var showMarker = showNewMarker;

        var map = new GMap2(document.getElementById("googlemap"));

        map.setCenter(new GLatLng(50.401515,-4.866943), 8);

        GEvent.addListener(map,"click", function(overlay,latlng) {     
            if (latlng) {   
                var myHtml = "" + latlng ;
                split=myHtml.indexOf(",");       
                x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
                y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
                document.collector.latitude.value=x;
                document.collector.longitude.value=y;
                lat="<br />Latitude: " + x;
                lon="<br />Longitude: " + y;
                latlon=""+lat+lon;

                //map.openInfoWindow(latlng, latlon);
                map.clearOverlay();
                showMarker(latlng);
            }
        });
        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMapTypeControl());
    }
}

它通过使用包含对函数的引用的变量showMarker来工作.首先指向函数showNewMarker,该函数创建一个标记,将其添加到地图,然后更改showMarker指向函数updateExistingMarker,该函数仅使用setLatLng将标记移动到新的位置.这意味着,在随后的点击中,现有标记将被移动到该点击的位置.

It works by using a variable, showMarker, containing a reference to a function. This starts out pointing to a function, showNewMarker, which creates a marker, adds it to the map, and then changes showMarker to point to the function updateExistingMarker, which simply uses setLatLng to move the marker to a new position. This means that, on subsequent clicks, the existing marker will be moved to the location of the click.