1

I want to display popup with the data item, such as: name, coordinates, stationID, Attribute.

But my code has some problem that can't run.

<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
          integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
          crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
            integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
            crossorigin=""></script>
    <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
    <div id="map" style="height: 500px; border: 1px solid #AAA;"></div>
    <script>

        var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            osmAttrib = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            osm = L.tileLayer(osmUrl, { maxZoom: 20, attribution: osmAttrib });
        var map = L.map('map').setView([24.151687694799833,120.64116954803465
              ], 15).addLayer(osm);              //顯示地圖
        L.control.scale().addTo(map);

        $.getJSON("https://sta.ci.taiwan.gov.tw/STA_Rain/v1.0/Things?$expand=Locations&$select=name,properties&$count=true", function (data) {
            var markerGroup = L.featureGroup();
            data.value.forEach(function (itemData, itemInd) {
                var latLng = L.latLng(itemData.Locations[0].location.coordinates[1], itemData.Locations[0].location.coordinates[0]);
                var myMarker = L.marker(latLng).addTo(markerGroup);
                myMarker.bindPopup('ID: ' + itemData.properties.stationID + '<br />Name: ' + itemData.properties.stationName);  

                onEachFeature (itemData, layer) {
                    layer.bindPopup("<p></p>"
                        + itemData.name + "</p>"
                        + itemData.properties.Attribute +
                        "</p>Attribute: "
                    );
                };
            }).addTo(map);

            markerGroup.addTo(map);
            map.fitBounds(markerGroup.getBounds());          
        });
    </script>
</body>
</html>

This is my GeoJSON:

https://sta.ci.taiwan.gov.tw/STA_Rain/v1.0/Things?$expand=Locations&$select=name,properties&$count=true
  • 1
    Can you describe with a little more detail what you mean by 'can't run'? Do you get any errors in console? – TomazicM Jul 22 at 6:33
  • Can't run means my leaflet didn't display nothing,after I add this code : onEachFeature (itemData, layer) { layer.bindPopup("<p></p>" + itemData.name + "</p>" + itemData.properties.Attribute + "</p>Attribute: " ); }; }).addTo(map); – wei shiuan Jul 22 at 6:35
  • Sorry, is my code has any error? – wei shiuan Jul 22 at 6:37
  • @TomazicM Should I use if loop? – wei shiuan Jul 22 at 6:43
  • What do you want to achieve with this statement (which is completely out of place in this case)? Popup is already bound to marker with myMarker.bindPopup. – TomazicM Jul 22 at 6:48
1

As already explanied in answer to this question Why the icon can't display with my JSON data on Leaflet, your JSON is not GeoJSON, so it's not converted to features and standard feature methods cannot be used.

Properties that you want to display in popup are members of itemData.properties object, so you have to iterate through itemData.properties keys and construct your popup by getting key values:

$.getJSON("https://sta.ci.taiwan.gov.tw/STA_Rain/v1.0/Things?$expand=Locations&$select=name,properties&$count=true", function (data) {
    var markerGroup = L.featureGroup();
    data.value.forEach(function (itemData, itemInd) {
        var latLng = L.latLng(itemData.Locations[0].location.coordinates[1], itemData.Locations[0].location.coordinates[0]);
        var myMarker = L.marker(latLng).addTo(markerGroup);
        var popupContent = '';
        for (var key in itemData.properties) {
          popupContent = popupContent + key + ':  ' + itemData.properties[key] + '</br>';        
        };
      myMarker.bindPopup(popupContent);
    }).addTo(map);

    markerGroup.addTo(map);
    map.fitBounds(markerGroup.getBounds());          
});
  • Sorry,I try to run,but this code can't run correct. It's also can't display the marker. Should I change the "key" ? – wei shiuan Jul 23 at 0:47
  • What does it mean "can't run correct"? – TomazicM Jul 23 at 5:24
  • I use your code you give me, and even the marker can't display. Before I use the above code(in my artical),the marker can display on the map. Sorry, iterate through itemData.properties keys and construct your popup by getting key values: this sentences I can't understand – wei shiuan Jul 23 at 6:05
  • Do you get any error in debug console? – TomazicM Jul 23 at 6:22
  • no. So I want to ask you the code you give me, popupContent = popupContent + key + ': ' + itemData.properties[key] + '</br>'; Should I change the key ? – wei shiuan Jul 23 at 6:24
0

I see a few issues:

  1. Data is not really GeoJSON, check http://geojsonlint.com/ to see if your data displays. The URL you posted has issues.

  2. In your script area, you are using Leaflet 1.5.1 and Leaflet 0.7.3. You don't need the older version.

  3. Here is a simple write up for displaying GeoJSON data, it may help. http://www.gistechsolutions.com/leaflet/DEMO/Simple/indexMap1.html You are bring your data in like it's just JSON not GeoJSON. You don't need to loop through your data for it to display real GeoJSON data, the Leaflet code handles this.

If you want to do this as JSON here is an example:

<!DOCTYPE html>
<html>
<head>
    <title>JSON - Leaflet</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
          integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
          crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
            integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
            crossorigin=""></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

    <style>
        #map {
            width: 800px;
            height: 600px;
        }
    </style>

</head>
<body>
<div id='map'></div>
<script>

//var url = 'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=42.837849&longitude=-73.77132&radius=80.45&maxResults=50&country=us&language=en-us&showClosed=&hours24Text=Open%2024%20hr';   

var url = 'MCDon.json'; //used the above URL to create this local JSON file and avoid CORs error.

        var map = L.map('map').setView([42.787,  -73.69216], 10); 

    var osm=new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{ 
                attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

    var mcd = L.featureGroup();

    $.getJSON(url, function(data) {
        for (i = 0; i < data.features.length; i++) { 
            var lng = data.features[i].geometry.coordinates[0];
            var lat = data.features[i].geometry.coordinates[1];
            var Line1 = data.features[i].properties.addressLine1;
                        var Line2 = data.features[i].properties.addressLine2;
                        var MCDs = L.marker([lat,lng]).bindPopup("&ltb&gtAddress: &lt/b&gt" + Line1 + "&lt/br&gtRegion: " + Line2);
            mcd.addLayer(MCDs);
        } 
    });
    mcd.addTo(map);

</script>
</body>
</html>

Note my URL issues a CORS error, so I used it to create a JSON file, and I used that instead. This example works with that data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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