My JSON file:
[
{
"coordinate": [45.464743, 9.189135799999999],
"Indirizzo": "Bike Sharing P.za Duomo Milano"
},
{
"coordinate": [45.4664299, 9.1976032],
"Indirizzo": "Bike Sharing P.za S.Babila Milano"
},
{
"coordinate": [45.454943, 9.162632600000002],
"Indirizzo": "Bike Sharing P.za Cadorna Milano"
},
...
]
I want to make a map with OpenStreetMap and add a marker for every coordinate's address.
I tried this:
<div id="map_id" style="width:100%;height:500px;"></div>
<script>
var map_var = L.map('map_id').setView([45.4642700, 9.1895100], 16);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map_var);
L.marker([45.4642700, 9.1895100]).addTo(map_var)
.bindPopup('Milan')
.openPopup();
$.getJSON( "bike_coordinate.json", function(json1) {
$.each(json1, function(key, data) {
for (var i = 0; i < json1.length; i++) {
var place = json1[i];
// Creating a marker and putting it on the map
var customIcon = L.icon({
iconSize: [38, 40], // size of the icon
iconAnchor: [10, 40], // point of the icon which will correspond to marker's location
popupAnchor: [5, -40] // point from which the popup should open relative to the iconAnchor
});
var marker = L.marker(place.coordinate, {icon: customIcon});
marker_array.push(tmp_marker);
tmp_marker.addTo(map_var).bindPopup(place.Indirizzo);
}
});
});
</script>
But it only shows the first marker that is not read in bike_coordinate.json. I've got this error:
Uncaught ReferenceError: $ is not defined at (index):217
$.each()
is sufficient here, you don't need a for
loop inside of it; the data
parameter of the $.each()
callback function holds the data for the place
object:
$.getJSON( "bike_coordinate.json", function(json1) {
$.each(json1, function(key, data) {
var place = data;
// Creating a marker and putting it on the map
var customIcon = L.icon({
iconSize: [38, 40], // size of the icon
iconAnchor: [10, 40], // point of the icon which will correspond to marker's location
popupAnchor: [5, -40] // point from which the popup should open relative to the iconAnchor
});
var marker = L.marker(place.coordinate, {icon: customIcon});
marker.addTo(map_var).bindPopup(place.Indirizzo);
});
});
If you read and iterate the data correctly all you need is to adapt your code and assign the markers. Include the required libraries such as jQuery and place the file under "/resources" so it can be read.