1

I tried many time, but the icon didn't show on the map. I want to know what the problem on my code.

This is my code:

<!DOCTYPE html>
<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.3.4/dist/leaflet.css"
          integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
          crossorigin="" />

    <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"
            integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA=="
            crossorigin=""></script>

    <script src="C:\ICBHI\test\leaflet.ajax.min.js"></script>
    <script src="C:\ICBHI\test\jquery-1.9.1.min.js"></script>
    <script src="C:\ICBHI\test\leaflet-providers.js"></script>


    <script src="https://sta.ci.taiwan.gov.tw/STA_Rain/v1.0/Things?$expand=Locations&$select=name,properties&$count=true"
            async defer></script>
</head>

<body>
    <div id="map" style="height: 500px; border: 1px solid #AAA;"></div>

</body>

</html>

<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.161707, 120.646675], 15).addLayer(osm);
    L.control.scale().addTo(map);



    $.getJSON('C:\leaflet plugin\json2.json' + id_device + '', function (data) {
        window.geojson = L.geoJson(data, {
            onEachFeature: function (feature, layer) {
                var Icon = L.icon({
                    iconUrl: 'https://www.vectorstock.com/royalty-free-vector/location-pin-icon-on-transparent-location-pin-vector-20942049',
                    iconSize: [45, 30], // size of the icon
                    style: style,
                });
                layer.setIcon(Icon);
                layer.bindPopup(feature.properties.date + '<br />' + feature.properties.id);
            }
        });
    });
    map.addLayer(geojson);

This is my JSON file:

    {
  "value": [
    {
      "name": "雨量站_open-C0A560-福山",
      "properties": {
        "stationID": "C0A560",
        "stationName": "福山",
        "areaDescription": "新北市烏來區",
        "city_SN": "06",
        "town_SN": "061",
        "Attribute": "局屬無人測站"
      },
      "Locations": [
        {
          "name": "雨量站-C0A560-新北市烏來區福山",
          "description": "雨量站-C0A560-新北市烏來區福山",
          "encodingType": "application/vnd.geo+json",
          "location": {
            "type": "Point",
            "coordinates": [ 121.4946, 24.7783 ]
          }     
        }
      ]
    },
    {
      "name": "雨量站_open-C0X190-安平",
      "properties": {
        "stationID": "C0X190",
        "stationName": "安平",
        "areaDescription": "臺南市安平區",
        "city_SN": "04",
        "town_SN": "276",
        "Attribute": "局屬無人測站"
      },
      "Locations": [
        {
          "name": "雨量站-C0X190-臺南市安平區安平",
          "description": "雨量站-C0X190-臺南市安平區安平",
          "encodingType": "application/vnd.geo+json",
          "location": {
            "type": "Point",
            "coordinates": [ 120.1441, 22.995 ]
          }
        }
      ]
    },
    {
      "name": "雨量站_open-C1F9E1-龍安",
      "properties": {
        "stationID": "C1F9E1",
        "stationName": "龍安",
        "areaDescription": "臺中市新社區",
        "city_SN": "02",
        "town_SN": "119",
        "Attribute": "局屬無人測站"
      },
      "Locations": [
        {
          "name": "雨量站-C1F9E1-臺中市新社區龍安",
          "description": "雨量站-C1F9E1-臺中市新社區龍安",
          "encodingType": "application/vnd.geo+json",
          "location": {
            "type": "Point",
            "coordinates": [ 120.8239, 24.1619 ]
          }
        }
      ]
    }
  • This is a race condition. You're trying to add the L.GeoJSON instance before it's created. Move map.addLayer(geojson); inside the (async) callback function for the $.getJSON call. – IvanSanchez Jul 11 at 10:40
2

IvanSanchez is rigt about first problem: layer with markers has to be added to the map inside the (async) callback function for the $.getJSON call.

Bill Chappell is right about danger of using absolute path to resources. Paths should be always relative to the main HTML page with the map. Best practice is to put them in subfolders of folder with map HTML page. So if all data files are in subfolder data, data file is simply referenced as 'data/json2.json', and if all libraries are subfolder lib, library file is referenced as 'lib/leaflet.ajax.min.js'.

But the main problem is that data file is not GeoJSON, but only JSON, so data has to be extracted by knowing it's structure to get needed properties and coordinates from it.

So to put markers with popups on the map code should look something like example below (tested, data url taken from first question that was put on hold). Note that coordinates had to be swaped. They are [lng, lat], but Leaflet expects [lat, lng].

$.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);
  });
  markerGroup.addTo(map);
  map.fitBounds(markerGroup.getBounds());
});
2

This is also an issue:

<script src="C:\ICBHI\test\leaflet.ajax.min.js"></script> 
<script src="C:\ICBHI\test\jquery-1.9.1.min.js"></script>
<script src="C:\ICBHI\test\leaflet-providers.js"></script>

These should be off a web site. I'm betting if I view the site from another PC, those files are not on my C:\ drive, so they won't run. You need to either use CDN's or put them in your web site folder and refer to them properly.

Same issue, you need to access your files by url not file path. That will only work from your PC.

$.getJSON('C:\leaflet plugin\json2.json' + id   //Same issue here. 

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.