如何在Google地图上专门删除标记

问题描述 投票:0回答:1

我正在开发一个包含谷歌地图,标记列表和两个按钮(添加/删除)的JavaScript应用程序。我想在地图和列表上添加标记,在列表中单击时删除。

可以添加但无法删除它。

添加按钮运行该功能。

 function add(id, address, lat, lon) {

  var id = $('#liste li').length + 1;
  $('#liste').append('<li id="'+id+'"><h2>id</h2><p>'+ address+" "+lat+" "+lon+'</p></li>'); //adds on list


  marker = new google.maps.Marker({ //adds marker on maps
  position: new google.maps.LatLng(lat, lon),
  animation: google.maps.Animation.DROP,
  id: id,                  //to get the marker individually
  icon: icons[destek].icon,
  info: new google.maps.InfoWindow({
    content: id +". " + adres
  }),
  map: map
});

google.maps.event.addListener(marker, 'click', function() {
  marker.info.open(map, marker);
});

map.panTo(marker.getPosition());
}

删除按钮运行该功能

function sil(id) {
$('#'+id).remove();
 var marker = marker({id:id}) //tried to get marker by id
marker.setMap(null);

 }

我如何具体获取和删除标记?谢谢。

javascript google-maps google-maps-api-3 google-maps-markers
1个回答
0
投票

通常,想法是跟踪全局变量中的所有标记 - 数组是最佳选择。每次调用函数add时,它应该将标记添加到此全局变量,或者应该使用返回值(如此处)来填充数组。

当试图移除特定标记时,很容易迭代数组以找到感兴趣的标记。

function add(id, address, lat, lon) {

    var id = $('#liste li').length + 1;
    $('#liste').append('<li id="'+id+'"><h2>id</h2><p>'+ address+" "+lat+" "+lon+'</p></li>'); //adds on list


    marker = new google.maps.Marker({ //adds marker on maps
        position: new google.maps.LatLng(lat, lon),
        animation: google.maps.Animation.DROP,
        id: id,                  //to get the marker individually
        icon: icons[destek].icon,
        info: new google.maps.InfoWindow({
            content: id +". " + adres
        }),
        map: map
    });
    google.maps.event.addListener(marker, 'click', function() {
      marker.info.open(map, marker);
    });

    map.panTo(marker.getPosition());

    /* either return the marker or add to array here... */
    return marker;
}



let markers=[];

/* some calls to `add` - return value is added to the array */
markers.push( add( 'bob', 'an address, some town, somewhere', 34.1, 2.7 ) );
markers.push( add( 'rita', 'The Brown Bull Inn, England', 51.473658, -0.911651 ) );
markers.push( add( 'sue', 'Muddy Field, The Back Lane, Scotland', 56.617411, -2.921294 ) );



/* to remove a marker by id - not tested btw */
const removemarker=function( id ){
    markers.forEach( function( mkr,index ){
        if( mkr.id===id ){
            mkr.setMap( null );
            markers.splice(index,1)
        }
    })
}

除了使用===而不是==,我对此没有任何问题。我创建了一个小小的演示程序,您可以尝试使用稍微修改过的函数(使用==而不是===

不要担心数据或改变的add功能 - 重要的是实际删除标记。这些数据来自我多年前做的一个项目,而add函数是你原版的一个非常简化的版本..应该很容易使用你之前建议的函数。

复制以下内容,添加自己的API密钥并运行以查看结果

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Remove Google Maps Marker</title>
        <style>
            #map{width:60%;height:60vh;margin:20vh auto;float:none;}
            a{margin:0.25rem auto;float:none;padding:0.25rem;}
        </style>
        <script>
            let map;
            let markers=[];
            let data={
                "table": "maps",
                "rows":
                [
                    {
                        "id": 96,
                        "name": "Kinnettles 4 x 125m turbines",
                        "lat": "56.61543329027024",
                        "lng": "-2.9266123065796137"
                    },
                    {
                        "id": 97,
                        "name": "Nathro 17 x 135m turbines",
                        "lat": "56.793249595719956",
                        "lng": "-2.8623101711273193"
                    },
                    {
                        "id": 98,
                        "name": "Ark Hill - 8 x 81m turbines",
                        "lat": "56.57065514278748",
                        "lng": "-3.0511732892761074"
                    },
                    {
                        "id": 99,
                        "name": "Dodd Hill - 5 x 125m turbines",
                        "lat": "56.54251020079966",
                        "lng": "-2.9051538305053555"
                    },
                    {
                        "id": 100,
                        "name": "Govals - 6 x 87m turbines",
                        "lat": "56.582320876071854",
                        "lng": "-2.9509015874633633"
                    },
                    {
                        "id": 101,
                        "name": "Carsegownie - 1 x78m turbine",
                        "lat": "56.67951330362271",
                        "lng": "-2.8062983350524746"
                    },
                    {
                        "id": 102,
                        "name": "Frawney - Over Finlarg - 5x100m turbines",
                        "lat": "56.56806620951482",
                        "lng": "-2.9501720266113125"
                    },
                    {
                        "id": 103,
                        "name": "North Tarbrax - 1 x 45m turbine",
                        "lat": "56.57144715546598",
                        "lng": "-2.92476614282225"
                    },
                    {
                        "id": 104,
                        "name": "The Carrach - 9 x 84m turbines",
                        "lat": "56.6938437674986",
                        "lng": "-3.131382067657455"
                    },
                    {
                        "id": 105,
                        "name": "Glaxo - 2 x 132m turbines",
                        "lat": "56.70431711148748",
                        "lng": "-2.4660869436035"
                    }
                ]
            };


            function initMap(){
                let location=new google.maps.LatLng( 56.617411, -2.921294 );
                map = new google.maps.Map( document.getElementById('map'), {
                    center: location,
                    zoom: 8
                });

                const removemarker=function( id ){
                    markers.forEach( function( mkr,index ){
                        if( mkr.id==id ){
                            mkr.setMap( null );
                            markers.splice(index,1)
                        }
                    })
                }
                const add=function(id,address,lat,lng){
                    return new google.maps.Marker({
                        id:id,
                        title:address,
                        position: new google.maps.LatLng(lat,lng),
                        title:address,
                        map:map
                    });
                }

                data.rows.forEach( obj=>{
                    markers.push( add( obj.id, obj.name, obj.lat, obj.lng ) );
                    let a=document.createElement('a');
                        a.id=obj.id;
                        a.innerHTML='Delete ['+obj.name+']';
                        a.href='#';
                        a.onclick=function(e){
                            e.preventDefault();
                            removemarker( this.id );
                            this.parentNode.removeChild( this );
                        };

                    document.getElementById( 'links' ).appendChild( a )
                })
            }
        </script>
        <script async defer src="//maps.google.com/maps/api/js?key=xxxxxxxxxxxxxxxx3ukaTnzBdDextWai4&callback=initMap"></script>
    </head>
    <body>
        <div id='map'></div>
        <div id='links'></div>
    </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.