外部GeoJSON图层的Leaflet自定义标记

时间:2017-09-10 17:09:52

标签: javascript maps leaflet geojson

我是Leaflet的新手,我正在尝试使用自定义标记设置外部geoJSON Feed。

我在下面的代码中将此添加到UOSensorsLayer时遇到问题。关于我的实现,官方文档不太清楚。我只能使用默认的小叶蓝色标记显示标记。

<html>
<head>
<title>Leaflet Map GeoJSON with Click Feature</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<style>
    #map {
        width: 100%;
        height: 100%;
    }
</style>
</head>
<body>
<div id='map'></div>
<script>

var UOSensors = $.ajax({
    url:"http://uoweb1.ncl.ac.uk/api/v1/sensors.geojson?api_key=j5wze84qf82y23luzkboejai2tqcdiqtpmu5swbq46r6s1cqtc86zhkctkbxf6chx8lqrxficjqt00kvwioukj81av",
    dataType: "json",
    success: console.log("Urban Observatory Sensor data successfully loaded."),
    error: function (xhr) {
        alert(xhr.statusText)
    }
})
// Specify that this code should run once the data request is complete
$.when(UOSensors).done(function() {

var map = L.map('map');

cartodbAttribution = '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>';

L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYW5keXByb2N0b3IiLCJhIjoiY2o2amZqODVyMTdoMzJxcWJlbnpzaHJqMiJ9.tFlpAR14eZXbEzpDx03c5Q', {
    attribution: cartodbAttribution
}).addTo(map);

var myIcon = L.icon({
    iconUrl: 'rain-marker.png',
    iconSize: [32, 37],
    iconAnchor: [16, 37],
    popupAnchor: [0, -28]
});

function WeatherFilter(feature, layer) {
  if(feature.properties.type === "Weather") return true;
}

var UOSensorsLayer = L.geoJSON(UOSensors.responseJSON, {filter: WeatherFilter})
    .eachLayer(function (layer) {
        layer.bindPopup(layer.feature.properties.name);
}).addTo(map);

map.setView({ lat: 54.96, lng: -1.61 }, 12);

});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我在我的案子中所做的并且对我来说完美的工作是:

var UOSensorsLayer = L.geoJSON(UOSensors.responseJSON), {
    filter : [...],
    pointToLayer: function (feature, latlng) {
        // For each point we return a marker with settings we want
        return L.marker(latlng, {icon: myIcon}).bindTooltip(tooltip).bindPopup(popup);
    }
}).addTo(map);