简体   繁体   中英

Leaflet get id from geojson and bind it to popup

 var map = L.mapbox.map('map', undefined, options); map.setView([56.413300, 8.869450], 16) var markerpositions; map.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/satellite-streets-v9')); // L.Control.geocoder().addTo(map); var geocoder = L.control.geocoder('search-MKZrG6M').addTo(map); L.marker([56.41083875205333, 8.864636421203615], {icon: HydrantIcon}).addTo(map).bindPopup("Hydrant 1"); L.marker([56.41069629842804, 8.868584632873537], {icon: HydrantIcon}).addTo(map).bindPopup("Hydrant 2"); L.marker([56.40941419180167, 8.866181373596193], {icon: HydrantIcon}).addTo(map).bindPopup("Hydrant 3"); var data = <?php echo JSON_encode($geojson); ?>; var geoJsonLayer = L.geoJson().addTo(map); function requestGeoJson(){ fetch('https://laerkeholt.dk/admin/get-features') .then(function(response){ return response.json() }) .then(function(json){ geoJsonLayer.clearLayers().addData(json).bindPopup('ID: + IDHERE'); var http = new XMLHttpRequest(); var url = "https://maker.ifttt.com/trigger/vandingsmaskine/with/key/"; http.open("POST", url, true); http.send(JSON.stringify({"value1": "ID 1"})); var hydrat1 = [56.41083875205333, 8.864636421203615]; var hydrat2 = [56.41069629842804, 8.868584632873537]; var hydrat3 = [56.40941419180167, 8.866181373596193]; var test = L.latLng(json).distanceTo(hydrat1); <?php echo $test ?> setTimeout(requestGeoJson, 5000); }); }; requestGeoJson();

So basically I want to have it so geoJsonLayer binds a popup with the id it got for the response JSON so each marker would be assigned its specific id from the response JSON. I have tried todo json.properties.id to try and get the ID

You can use either pointToLayer or onEachFeature for this.

When you instantiate the geoJSON layer, use this:

var geoJsonLayer = L.geoJson(false, {onEachFeature: addMyPopup}).addTo(map);

// Initialise the three reference points
var hydrat1 = L.latLng(<..>, <..>);
var hydrat2 = L.latLng(<..>, <..>);
var hydrat3 = L.latLng(<..>, <..>);

// This gets called for every point in the GeoJSON
function addMyPopup ( feature, layer) {
if ((layer.getLatLng().distanceTo(hydrat1) < 5)
  ||(layer.getLatLng().distanceTo(hydrat2) < 5)
  ||(layer.getLatLng().distanceTo(hydrat3) < 5)) {
    // Do something
  }
  layer.bindPopup("My ID is: " + feature.properties.id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM