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.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
AliceG
  • 83
  • 1
  • 7
  • 1
    May be you looking for [this](https://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – Empty Brain Jul 03 '18 at 11:09
  • I don't understand how to adapt it to my problem, I post a test below @EmptyBrain – AliceG Jul 03 '18 at 11:27
  • I post it below but it doesn't work @chŝdk I don't understand how write it correctly – AliceG Jul 03 '18 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 Jul 03 '18 at 11:35
  • @AliceG I posted an answer, to point out your problem. – cнŝdk Jul 03 '18 at 11:37
  • 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? – dougajmcdonald Jul 03 '18 at 12:06
  • @dougajmcdonald I've got this error: Uncaught ReferenceError: $ is not defined at (index):217 – AliceG Jul 03 '18 at 12:26
  • That's another problem, you haven't included jQuery in the page, put this in the header of your page : ``. – cнŝdk Jul 03 '18 at 12:30
  • Yes as per the comment above you need to include jQuery on you page. That's what give you the $ variable – dougajmcdonald Jul 03 '18 at 12:33
  • The problem now is that it can't find the file, is it correct to put the file on the same folder of the app python? – AliceG Jul 03 '18 at 12:34
  • @AliceG You need to put it under your `/resources/ ` directory. – cнŝdk Jul 03 '18 at 12:37
  • @chŝdk I tried in the folder of the running app, I tried in the static folder and I tried in the templates folder but nothing change – AliceG Jul 03 '18 at 12:44
  • Can you share a screenshot with yoour project structure? – cнŝdk Jul 03 '18 at 12:45
  • @chŝdk I managed to get it find the file, every step a new problem ahah: Uncaught TypeError: Cannot read property 'lat' of null at Object.project (leaflet.js:5) at Object.latLngToPoint (leaflet.js:5) at e.project (leaflet.js:5) ... – AliceG Jul 03 '18 at 12:52
  • Try to use `console.log(data)` inside the loop and debug the loop iterations and check if `marker`object isn't `null`. – cнŝdk Jul 03 '18 at 12:58
  • @chŝdk It solves my problem, thanks a lot!!! – AliceG Jul 03 '18 at 13:01

2 Answers2

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

nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • 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 Jul 03 '18 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 Jul 03 '18 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 Jul 03 '18 at 12:07
  • You can open your browser dev tools and check in the Network tab if your file is loaded or not. – nikoshr Jul 03 '18 at 12:14
  • I found this in corrispondence to $.getJSON( "bike_coordinate.json", function(json1) { : Uncaught ReferenceError: $ is not defined at (index):217 – AliceG Jul 03 '18 at 12:24
  • Then you're not loading jQuery. Add `` somewhere before your script – nikoshr Jul 03 '18 at 12:25
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.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78