I am currently building a leaflet map where I will implement a bunch of markers with popups. I want all of my markers and popups stored in an external file to keep the code as clean as possible. My question is, how can I achieve this? Do I create a geojson file with the markers and popups and if so, how do I load such a geojson into my html file if I want the geojson file to be stored locally (avoiding CORS policy error) ? What other options do I have? Thanks for the help in advance!
Advertisement
Answer
You can edit your geojson data here: https://geojson.io/ and then create a js file where you assign your geojson data (copied from geojson.io) to a variable:
var geojsondata = ... // your geojson data
Then create a html file with another js file, where you read and display your geojson (read the leaflet documentation for more info):
var readfromjson = L.geoJSON(geojsondata).addTo(map);
That is how you load markers. If you want to have also popups to every marker you need to add some properties to every marker by creating a table in geojson.io with the table name popup for example (a popup to one marker could be ‘I am a popup’ (must be html)). Now to access these properties in your code:
var readfromjson = L.geoJSON(geojsondata, { onEachFeature: function (feature, layer) { if (feature.properties && feature.properties.popup) { layer.bindPopup(features.properties.popup) } } }).addTo(map);