Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull GeoJSON data into Leaflet with AJAX call

So I'm trying to publish a MapBox map with Leaflet, and want to add some markers from an external data source with an AJAX call. Specifically, I'm mapping out all of the wifi spots in NYC with this data set. I see where it says I can download the wifi locations in JSON, but I'm still trying to teach myself how to code and don't know what to do from there.

Here's the example that MapBox gives using a .js hosted on your site directory. What would it look like if I were to do an AJAX call instead?

<script src="museums.js"></script>
<script type="text/javascript">
// Define a GeoJSON data layer with data
var geojsonLayer = new L.GeoJSON();

// Display the name property on click
geojsonLayer.on('featureparse', function (e) {
    if (e.properties && e.properties.name){
    e.layer.bindPopup(e.properties.name);
}
});

geojsonLayer.addGeoJSON(data);

// Add the GeoJSON layer
map.addLayer(geojsonLayer);
</script>
like image 423
geraldarthur Avatar asked Aug 06 '12 16:08

geraldarthur


1 Answers

Following your link to wifi spot data set show me that you can call the json data from this url: wifi spot

The problem is that the resulting json is not formated in GEOJSON format (Wikipedia)...

In the case you effectively has an url giving you valid GEOJSON, you could use jQuery to make the Ajax call in the following way:

$.ajax({
    type: "POST",
    url: "https://nycopendata.socrata.com/api/views/ehc4-fktp/rows.json",
    dataType: 'json',
    success: function (response) {

        geojsonLayer = L.geoJson(response, {
            style: yourLeafletStyle
        }).addTo(map);
    }
});

Regards

Etienne

like image 152
Etienne Desgagné Avatar answered Nov 01 '22 23:11

Etienne Desgagné