简体   繁体   中英

How to delete marker specificly on Google Maps

I am developing a javascript app that contains google map, marker list and two button (add/delete). i want to add marker on map and the list, to delete in both when clicked on list.

it's okay to add but can not delete it.

add button runs that function.

 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());
}

delete button runs that function

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

 }

how can i get and delete marker specificly? thanks.

Generally the idea would be to track all the markers in a global variable - an array is the best choice. Each time the function add is called it should either add the marker to this global variable or the return value ( as here ) should be used to populate the array.

When trying to remove a specific marker it is easy then to iterate through the array to find the marker of interest.

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)
        }
    })
}

Aside from the use of === rather than == I had no issues with this. I created a little demo which you can try with a slightly modified function (using == rather than === )

Don't worry about the data or the altered add function - the important bit is the actual removal of the marker. The data is from a project I did years ago and the add function is a very simplified version of your original.. should be easy to get this working with your function as suggested previously.

Copy the following, add your own API key and run to see the results

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM