Leaflet Markers + clustering非常慢,jsfiddle演示(200-400标记)

时间:2017-12-11 22:08:39

标签: javascript leaflet gis

这是我的剧本,我目前的传单很糟糕,加载我的标记需要花费大量时间,但我一次只玩200-500似乎无法找到原因。

将标记从API中提取并存储到数组中,然后在点击地图上的某个部分时将其绘制到地图上,在实时演示中查看自己,它可以正常工作直到加载标记然后在缩放时开始滞后很多

如果有人为我提供解决方案,我将非常感激,因为我打算拥有比现在更多的标记。



 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);
}
&#13;
  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; }
&#13;
<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>
&#13;
&#13;
&#13;

0 个答案:

没有答案