1

here is my script, I'm currently having a bad time with leaflet, it is taking substantial amounts of time to load my markers yet I'm only playing with up to 200-500 at a time and can't seem to find the reason why.

Markers are pulled from an API and stored into an array then plotted onto the map upon clicking a section on the map, see for yourself on the live demo, it works fine until loading markers then it starts to lag a lot when zooming, See demo --> https://jsfiddle.net/jgov83fg/14/

Does anybody have a solution for me as I intend to have a lot more markers than it is currently pulling?

 var postcode;
var police_api_dates = [
  "&date=2017-03",
];
var completed_requests = 0;
var police_api_base_url = "https://data.police.uk/api/crimes-street/all-crime?poly=";
var crimes = [];
var count = 0;

var mymap = L.map('map').setView([53.7983587, -1.6191674], 11);
    mymap.createPane('labels');
    mymap.getPane('labels').style.zIndex = 650;
    mymap.getPane('labels').style.pointerEvents = 'none';


    var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
        attribution: '©OpenStreetMap, ©CartoDB'
}).addTo(mymap);

var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
        attribution: '©OpenStreetMap, ©CartoDB',
        pane: 'labels'
}).addTo(mymap);

    L.tileLayer('https://api.mapbox.com/styles/v1/adam97x/cjavcj1680vgz2sqshn70q5pg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWRhbTk3eCIsImEiOiJjamF2Y2k1NmswYzhuMnZtazlpNXU2NDExIn0.RifBBI5nelL-4d21mkn7Wg', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="http://mapbox.com">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(mymap);

        // control that shows state info on hover
    var info = L.control();
    info.onAdd = function (mymap) {
        this._div = L.DomUtil.create('div', 'info');
        this.update();
        return this._div;
    };

    info.update = function (properties) {
        this._div.innerHTML = '<h4>Highlighted Postcode</h4>' +  (properties ?
            '<b> Postcode: ' + properties.Name
            : 'Hover over a state');
    };

    info.addTo(mymap);

function style(feature) {
    return {
        fillColor: 'grey',
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.5
    };
}

L.geoJson(statesdata, {style: style}).addTo(mymap);

    function highlightFeature(e) {
        var layer = e.target;


        layer.setStyle({
            weight: 5,
            opacity: 1,
            color: '#000',
            dashArray: '',
            fillOpacity: 0.7
        });

        if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
            layer.bringToFront();
        }

        info.update(layer.feature.properties);
        postcode = layer.feature.properties.Name.substr(2)-1;
        console.log(postcode);

    }
    /*global statesdata*/
    var geojson;

    function resetHighlight(e) {
        geojson.resetStyle(e.target);
        info.update();
    }
            function zoomFeature(e) {
        mymap.fitBounds(e.target.getBounds());


        var colonString = statesdata
   .features[postcode]
   .geometry
   .coordinates[0]
   .map(pair => pair.reverse().join())
   .join(':');

     for (var a = 0; a < 1; a++){
    var request = police_api_base_url + colonString + police_api_dates[a]
    get_JSON(request, JSON_callback);
  }
    }
    function onEachFeature(feature, layer) {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight,
            click: zoomFeature
        });

    }

    geojson = L.geoJson(statesdata, {
        style: style,
        onEachFeature: onEachFeature
    }).addTo(mymap);

geojson.eachLayer(function (layer) {
    layer.bindPopup(layer.feature.properties.Name);


});

function JSON_callback(data){
  completed_requests++;
  var data_len = data.length;

  if (data[0] != undefined){
    for (var i = 0; i < data_len; i++){
      cat = data[i]["category"];
      lat = data[i]["location"]["latitude"];
      lng = data[i]["location"]["longitude"];
      if (cat in crimes) {
        crimes[cat]++;

      } else {
        crimes[cat] = 1;
      }
          create_marker(lat, lng);
    }
  }

  if (completed_requests == 1){
    console.log("Requests done");
    console.log(crimes);

  }
}

function create_crime_markers(lat, lng, cat){
  show_by_id("num_of_crimes_load_img");
  show_by_id("popular_crime_load_img");
  completed_requests = 0;
  num_of_crimes = 0;
  crimes = {};;
  for (var a = 0; a < 1; a++){
    var request = police_api_base_url + lat + "&lng=" + lng + police_api_dates[a]
    get_JSON(request, JSON_callback);

  }

}
var current_lat_lng = [];
function create_marker(lat, lng, title){
  current_lat_lng.push(lat, lng, cat);
  chunksize = 3;
var chunks = [];

current_lat_lng.forEach((item)=>{
  if(!chunks.length || chunks[chunks.length-1].length == chunksize)
  chunks.push([]);

  chunks[chunks.length-1].push(item);
});
var markers = L.markerClusterGroup({
    chunkedloading: true,
        spiderfyOnMaxZoom: true,
    showCoverageOnHover: false,
    zoomToBoundsOnClick: true,
    spiderfyDistanceMultiplier: 2.4

});
var markerList = [];
         for (var f = 0; f < chunks.length; f++) {
            var marker = new L.circleMarker([chunks[f][0],chunks[f][1]])
                  markerList.push(marker);
        }

        markers.addLayers(markerList);
        mymap.addLayer(markers);
}
  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
  .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }
<html>
<head>
<meta charset=utf-8 />
<title>KML Data</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.2.0/dist/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
<script type="text/javascript" src="https://project-adam97.c9users.io/asset/bd.js"></script>
<script src="https://project-adam97.c9users.io/asset/requests.js"></script>
</head>
<body>
<script> src='https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script>
 <script src="https://unpkg.com/leaflet.markercluster@1.2.0/dist/leaflet.markercluster.js"></script>
<div id='map'></div>


</body>
</html>
  • What takes long, the rendering or the loading? – bugmenot123 Dec 12 '17 at 12:59
  • Well if you check the Jsfiddle, when you click on a sector of the map everything will load then zooming and trying to move the map around it will be laggy as, sometimes even freezing up the browser / tab. – Savage Dec 12 '17 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.