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 = '© <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
Best Answer
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 throughitemData.properties
keys and construct your popup by getting key values: