Reputation: 267
I've setup a leaflet map with a mapbox style, which is loading an external GeoJson. That works fine, except it doesn't import any styling parameters from the GeoJson such as the marker-color. Like f.e. :
"properties": {
"marker-color": "#4de21b",
"marker-size": "medium",
Is shown in the default blue'ish marker-color after import. So that's the first issue. And I guess my second (and more important) issue is connected with this. I'd like to add an infobox-popup for each marker based on the geoJson. Is that possible and how?
Thanks for advice in advance!
My webcode:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script>
// Add AJAX request for data
var counties = $.ajax({
url:"https://myurl.net/wp-content/uploads/2020/02/geojson-example2.geojson",
dataType: "json",
success: console.log("County data successfully loaded."),
error: function (xhr) {
alert(xhr.statusText)
}
})
// Specify that this code should run once the county data request is complete
$.when(counties).done(function() {
var map = L.map('map')
.setView([51.1656914, 10.4515257], 5);
var basemap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses /by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/dark-v10',
accessToken: 'mytoken'}).addTo(map);
// Add requested external GeoJSON to map
var kyCounties = L.geoJSON(counties.responseJSON).addTo(map);
});
</script>
The GeoJson
{ "type": "FeatureCollection", "features": [
{
"type": "Feature",
"properties": {
"marker-color": "#4de21b",
"marker-size": "medium",
"marker-symbol": "",
"icon":"purpleIcon"
},
"geometry": {
"type": "Point",
"coordinates": [
10.52490234375,
51.631657349449995
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#af2ecf",
"marker-size": "medium",
"marker-symbol": ""
},
"geometry": {
"type": "Point",
"coordinates": [
9.47021484375,
52.17393169256849
]
} } ]}
Upvotes: 0
Views: 301
Reputation: 14570
You can use L.geoJSON
's pointToLayer
& onEachFeature
respectively to achieve the desired behavior by passing the color as an argument to return the desired marker icon and again by conditionally checking the geojson feature properties to generate the marker popup.
Below you can find a demo to illustrate the above mentioned by simulating a fake async call to retrieve the geojson as in your case.
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
</head>
<body>
<div id="mapid" style="height: 100vh;"></div>
<script>
var map = L.map("mapid").setView([51.1656914, 10.4515257], 7);
L.tileLayer(
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw", {
maxZoom: 18,
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: "mapbox/streets-v11",
tileSize: 512,
zoomOffset: -1
}
).addTo(map);
const geojson = {
type: "FeatureCollection",
features: [{
type: "Feature",
properties: {
"marker-color": "#4de21b",
"marker-size": "medium",
"marker-symbol": "",
icon: "purpleIcon"
},
geometry: {
type: "Point",
coordinates: [10.52490234375, 51.631657349449995]
}
},
{
type: "Feature",
properties: {
"marker-color": "#af2ecf",
"marker-size": "medium",
"marker-symbol": ""
},
geometry: {
type: "Point",
coordinates: [9.47021484375, 52.17393169256849]
}
}
]
};
const simulateAsyncCall = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(geojson);
}, 1000);
});
};
function onEachFeature(feature, layer) {
const popupContent = `I have marker color <b>${
feature.properties["marker-color"]
}</b>, and marker size <b>${feature.properties["marker-size"]}</b>`;
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
}
const icon = color =>
new L.Icon({
iconUrl: `https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${
color === "#af2ecf" ? "violet" : "green"
}.png`,
shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
simulateAsyncCall().then(geojson => {
console.log(geojson);
L.geoJSON(geojson, {
pointToLayer: function(feature, latlng) {
const color = feature.properties["marker-color"];
return L.marker(latlng, {
icon: icon(color)
});
},
onEachFeature
}).addTo(map);
});
</script>
</body>
</html>
Upvotes: 1