2

I've a json file like:

[
  {
    "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 openstreet map and add a marker for every coordinates and adress.

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: '&copy; <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 show the first marker that is not read in bike_coordinate.json, I think I write wrong code, can anyone help me, please?

I'm using openstreet map, leaflet. I'm new with javascript, thank you all.

16
  • 1
    May be you looking for this Commented Jul 3, 2018 at 11:09
  • I don't understand how to adapt it to my problem, I post a test below @EmptyBrain
    – AliceG
    Commented Jul 3, 2018 at 11:27
  • I post it below but it doesn't work @chŝdk I don't understand how write it correctly
    – AliceG
    Commented Jul 3, 2018 at 11:28
  • I tried it but it doesn't work @chŝdk I don't understand how write it correctly, I tried google maps, but it's not what I'm searching for, I want to use openstreet map that doesn't require API key
    – AliceG
    Commented Jul 3, 2018 at 11:35
  • 1
    If the example @nikoshr added isn't working for you I'd suspect you have some issues with somethibg like not including jQuery or the .json file not being where you expect it. What console errors do you have? Commented Jul 3, 2018 at 12:06

3 Answers 3

3

Your code reading the JSON file works just fine, it's how you work with the resulting data that's at fault:

  • you iterate twice over your array, once with $.each(json1, and a second time with for (i = 0; i < locations.length; i++) {. One of them must go.
  • you add a tmp_marker on your map that does not exist : use marker.addTo(map_var).bindPopup(place.Indirizzo); instead
  • you use a marker_arrayvariable that is not defined, remove it,
  • you declare a custom icon but you don't set a iconUrl : it's required and breaks Leaflet. For example:

    var customIcon = L.icon({
        iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
        iconSize:     [38, 40],
        iconAnchor:   [10, 40],
        popupAnchor:  [5, -40]
    }); 
    

You could write your code as

$.getJSON( "bike_coordinate.json", function(json1) {

     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({
            iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
            iconSize:     [38, 40], 
            iconAnchor:   [10, 40],
            popupAnchor:  [5, -40]
        }); 
        var marker = L.marker(place.coordinate, {icon: customIcon});
        marker.addTo(map_var).bindPopup(place.Indirizzo);
    }

});

And a demo https://plnkr.co/edit/PJi8HzqTJJTB5SnJJnak?p=preview

6
  • Thanks for help! I tried your code but it doesn't work in my script, I don't understand why in every case it doesn't add any marker. What can I control to make it works?
    – AliceG
    Commented Jul 3, 2018 at 11:53
  • The demo shows a working map that reproduces what you have in your question. Not much I can add, besides the point I've just added about marker_array. Can you modify my demo to reproduce your problem?
    – nikoshr
    Commented Jul 3, 2018 at 11:59
  • It's possible that the problem is that it can't find my file? But I've got json file both in the templates folder and app folder
    – AliceG
    Commented Jul 3, 2018 at 12:07
  • You can open your browser dev tools and check in the Network tab if your file is loaded or not.
    – nikoshr
    Commented Jul 3, 2018 at 12:14
  • I found this in corrispondence to $.getJSON( "bike_coordinate.json", function(json1) { : Uncaught ReferenceError: $ is not defined at (index):217
    – AliceG
    Commented Jul 3, 2018 at 12:24
2

Your problem here, is that you are using an extra loop, when you were trying to loop over the json items.

In fact the $.each() is sufficient here, you don't need to use a for loop inside of it, and the data param of the $.each() callback function will hold the data you need, to fill place object.

This is how should be your code:

$.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, then all you need is to adapt your code and assign the markers.

Edit:

Make sure to include all the required JS libraairies such as jQuery in your page and to place the file in the right directory under /resources, of your application so it can be read correctly.

7
  • Thanks for help! I tried your code but it doesn't work in my script, I don't understand why in every case it doesn't add any marker. What can I control to make it works?
    – AliceG
    Commented Jul 3, 2018 at 11:54
  • what does the error say? Post the errror stack trace please.
    – cнŝdk
    Commented Jul 3, 2018 at 12:07
  • It doesn't give me any error, I've only have any marker on the map
    – AliceG
    Commented Jul 3, 2018 at 12:10
  • Try to put console.log(data);inside the loop and see what it gives in the console, click F12to check it.
    – cнŝdk
    Commented Jul 3, 2018 at 12:16
  • I found this: Uncaught ReferenceError: $ is not defined at (index):217
    – AliceG
    Commented Jul 3, 2018 at 12:23
1

For those coming to this late via a search:

The code to define the customIcon should be outside the loop & function as it's definition is constant:

// Creating a marker and putting it on the map
    var customIcon = L.icon({
      iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
      iconSize: [38, 40],
      iconAnchor: [10, 40],
      popupAnchor: [5, -40]
    }); 

$.getJSON( "bike_coordinate.json", function(json1) {
   for (var i = 0; i < json1.length; i++) {
    var place = json1[i];
    var marker = L.marker(place.coordinate, {icon: customIcon});
    marker.addTo(map_var).bindPopup(place.Indirizzo);
    } 
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.