简体   繁体   中英

Need to remove marker in javascript & Ajax with Mapbox

I am trying to remove markers not centered on the map when I move on the map. I think it is related to the asynchronous side of Ajax.

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>A simple map</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.css' rel='stylesheet' />
    <style>
      body { margin:0; padding:0; }
      #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
  </head>
  <body>
    <div id='map'></div>
    <script>
      L.mapbox.accessToken = 'pk.eyJ1IjoiYmxhY2t5IiwiYSI6IjA4NWJjZDNiNDQ0MTg3YjVmZTNkM2NkMWQ3MmM4ZjU4In0.SDQh56AZPCbIL2rVs4eAkQ';
      var map = L.mapbox.map('map', 'mapbox.streets').setView([47, 2], 6);
      var markerGroup;

      map.on('moveend', function(move) {

        var coordinates = map.getCenter();

        markerGroup.clearLayers; //doesn't work.

            $.ajax({
              type: 'GET',
              url: 'http://private-anon-0b8fcf12d-cartoemploi.apiary-mock.com/geosearch/'+ coordinates.lat + ',' + coordinates.lng,
              crossDomain: true,
              dataType: 'json',
              contentType: "application/json",
              success: function(response) {
                $.each(response, function(i) {  
                  title = response[i].title;              
                  latitude = response[i].latitude;
                  longitude = response[i].longitude;

                  markerGroup = L.mapbox.featureLayer({

                  // this feature is in the GeoJSON format: see geojson.org
                  // for the full specification
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        // coordinates here are in longitude, latitude order because
                        // x, y is the standard for GeoJSON and many formats
                        coordinates: [
                          longitude,
                          latitude
                        ]
                    },
                    properties: {
                        title: title,
                        description : '',
                        // one can customize markers by adding simplestyle properties
                        // https://www.mapbox.com/guides/an-open-platform/#simplestyle
                        'marker-size': 'large',
                        'marker-color': '#ffa5ff',
                        'marker-symbol': 'suitcase'
                    }
                  }).addTo(map);
                });
              }
            });
      });

      ... some code
    </script>
  </body>
</html>

I tried this :

map.eachLayer(function (layer) {
    map.removeLayer(layer);
});

But this removes the entire map, which is not what I want.

I found my mistake. I created too much markers. I put markers in a array in my global variable markerGroup.

var markerGroup = [];

And I have created a function to empty my markerGroup.

function clearMarkers() {
    markerGroup.forEach(function(marker) {
        marker.clearLayers();
    });

    markerGroup = [];
  }

The full code :

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>A simple map</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.css' rel='stylesheet' />
    <style>
      body { margin:0; padding:0; }
      #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
  </head>
  <body>
    <div id='map'></div>
    <input id='search' class='search-ui' placeholder='' />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script>
    <script>
      L.mapbox.accessToken = 'pk.eyJ1IjoiYmxhY2t5IiwiYSI6IjA4NWJjZDNiNDQ0MTg3YjVmZTNkM2NkMWQ3MmM4ZjU4In0.SDQh56AZPCbIL2rVs4eAkQ';
      var map = L.mapbox.map('map', 'mapbox.streets').setView([47, 2], 6);

      var markerGroup = [];

      function clearMarkers() {
        markerGroup.forEach(function(marker) {
            marker.clearLayers();
        });

        markerGroup = [];
      }

      map.on('moveend', function(move) {

        var coordinates = map.getCenter();
        console.log(coordinates.lat)
        console.log(coordinates.lng)


            $.ajax({
              type: 'GET',
              url: 'http://private-anon-0b8fcf12d-cartoemploi.apiary-mock.com/geosearch/'+ coordinates.lat + ',' + coordinates.lng,
              crossDomain: true,
              dataType: 'json',
              contentType: "application/json",
              success: function(response) {
                clearMarkers();
                $.each(response, function(i) {  
                  title = response[i].title;              
                  latitude = response[i].latitude;
                  longitude = response[i].longitude;

                  markerGroup.push(L.mapbox.featureLayer({

                  // this feature is in the GeoJSON format: see geojson.org
                  // for the full specification
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        // coordinates here are in longitude, latitude order because
                        // x, y is the standard for GeoJSON and many formats
                        coordinates: [
                          longitude,
                          latitude
                        ]
                    },
                    properties: {
                        title: title,
                        description : '',
                        // one can customize markers by adding simplestyle properties
                        // https://www.mapbox.com/guides/an-open-platform/#simplestyle
                        'marker-size': 'large',
                        'marker-color': '#ffa5ff',
                        'marker-symbol': 'suitcase'
                    }
                  }).addTo(map));
                });
              }
            });
      });

      $(document).ready(function() {
        $.ajax({
          type: 'GET',
          url: 'http://private-anon-0b8fcf12d-cartoemploi.apiary-mock.com/emploi/',
          crossDomain: true,
          dataType: 'json',
          contentType: "application/json",
          success: function(response) {
            clearMarkers();
            $.each(response, function(i) {  
              title = response[i].title;              
              latitude = response[i].latitude;
              longitude = response[i].longitude

              markerGroup.push(L.mapbox.featureLayer({

              // this feature is in the GeoJSON format: see geojson.org
              // for the full specification
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    // coordinates here are in longitude, latitude order because
                    // x, y is the standard for GeoJSON and many formats
                    coordinates: [
                      longitude,
                      latitude
                    ]
                },
                properties: {
                    title: title,
                    description : '',
                    // one can customize markers by adding simplestyle properties
                    // https://www.mapbox.com/guides/an-open-platform/#simplestyle
                    'marker-size': 'large',
                    'marker-color': '#ffa500',
                    'marker-symbol': 'suitcase'
                }
              }).addTo(map));
            });
          }
        });
      });
    </script>

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