Giter VIP home page Giter VIP logo

leaflet-ajax's Introduction

leaflet-ajax

js-semistandard-style

Allows you to call JSON via an Ajax call with a jsonp fallback.

var geojsonLayer = new L.GeoJSON.AJAX("geojson.json");

for jsonp add the option "dataType" and set it to "jsonp"

var geojsonLayer = L.geoJson.ajax("http:webhost.fake/geojson.jsonp",{dataType:"jsonp"});

Note that data starts to download when the layer is created NOT when it’s added to the map in order to get a head start.

You may pass either a url string or an array of url strings if you want to download multiple things (handy if your downloading data from an ESRI based thing which will have separate line, point, and poly features).

As you see you can also use lower case methods without creating new objects

For weirder jsonp you can set "callbackParam" for if you need to change the name of the callback parameter to something besides "callback", e.g. Mapquest Nominative Open uses "json_callback" instead of "callback".

If you want to be able to load stuff from the file system (with appropriate custom flags set) set local to true.

If you want to set headers to the XMLHttpRequest set the 'headers' option equal to an object.

Gives off three events data:loading, data:progress and data:loaded.

  • data:loading fires before we start downloading things, note if the constructor is given a url it won't wait to be added to the map to start downloading the data, but it does do an async wait so you have time to add a listener to it (and so leaflet.spin will work with it).
  • data:progress is called each time a file is downloaded and passes the downloaded geojson as event data.
  • data:loaded is called when all files have downloaded, this is mainly different from data:progress when you are downloading multiple things.

You can also add a middleware function which is called after you download the data but before you add it to leaflet:

var geojsonLayer = L.geoJson.ajax("route/to/esri.json",{
    	middleware:function(data){
        	return esri2geoOrSomething(json);
    	}
    });

addUrl does not clear the current layers but adds to the current one, e.g.:

var geojsonLayer = L.geoJson.ajax("data.json");
geojsonLayer.addUrl("data2.json");//we now have 2 layers
geojsonLayer.refresh();//redownload the most recent layer
geojsonLayer.refresh("new1.json");//add a new layer replacing whatever is there

last but now least we can refilter layers without re adding them

var geojsonLayer = L.geoJson.ajax("data.json");
geojsonLayer.refilter(function(feature){
    return feature.properties.key === values;
});

Behind the scenes are two new classes L.Util.ajax = function (url) for same origin requests and L.Util.jsonp = function (url,options) cross origin ones. Both return promises, which have an additional abort method that will abort the ajax request.

L.Util.ajax("url/same/origin.xml").then(function(data){
	doStuff(data);
});
//or
L.Util.jsonp("http://www.dif.ori/gin").then(function(data){
	doStuff(data);
});

In related news L.Util.Promise is now a constructor for a promise, it takes one argument, a resolver function.

Some of the jsonp code inspired by/taken from this interesting looking plugin that I have failed to make heads nor tails of (the plugin, not the jsonp code)

leaflet-ajax's People

Contributors

calvinmetcalf avatar hugovk avatar sidonaldson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leaflet-ajax's Issues

example loading popup only some columns

Hi! this plugin is great,

the only thing i need to show only certain columns on the popup:

function popUp(f,l){
    var out = [];
    if (f.properties){
        for(key in f.properties){
            out.push(key+": "+f.properties[key]);
        }
        l.bindPopup(out.join("<br />"));
    }
}

i need to only bring 2 specific columns from the geojson:

column names are: 'name_depto' and 'postal'

thanks!!!

pointToLayer per feature

Hi

I think when using L.geoJson the pointToLayer is called per feature. But when using leaflet ajax, it only calls that once.

This prevents setting for eg, an icon according to the feature's properties.

Is there a way round this?

here is what I'm upto for clarification:

var features = new L.GeoJSON.AJAX("/features.json?circuit=555",{
    onEachFeature:onEachFeature,

    style: function (feature) {
			// called per feature:
			console.log(feature.properties.style.fillColor);
      return feature.properties && feature.properties.style;
    },
		
		pointToLayer: function (feature) {
			// only called once
      console.log(feature.properties.shape);
    },
});

Thanks for any advice

Compatibility with Browserify

Hi ! This module cannot be required with Browserify as it assumes L is defined and it redefines require, exports, etc. Would it be possible to make it compliant with Browserify ?

JSONP custom callbackParam ignored

When attempting to set a custom callback parameter for the URL, the custom parameter is ignored and leaflet-ajax instead uses the default parameter name of callback. The problem appears to be on line 534 in leaflet.ajax.js where you use cbParam instead of callbackParam.

Problem when using L.GeoJSON.AJAX() on google Chrome/Chromium

Hello,

I'm trying to open the attached html into chrome/chromium browser, but the geoJson added layers are not showing up. I've test on Firefox (Linux and Windows) and Microsoft Edge (Windows) and worked fine. Below you can see screenshots from Firefox and Chromium.

Chromium Version 65.0.3325.181: https://i.stack.imgur.com/TxAgU.png
Firefox 59.0.2: https://i.stack.imgur.com/O28I2.png

Can someone help me, please?

Thank you.

<!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="utf-8">
            <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
            <title>FazMaraneyRGB_transparent_mosaic_group1</title>

            <!-- Leaflet -->
            <link rel="stylesheet" href=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/leaflet.css />
            <script src=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/leaflet.js ></script>
            
            <!-- Leaflet.draw -->
            <link rel="stylesheet" href=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/draw/leaflet.draw.css />
			<script src=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/draw/leaflet.draw.js ></script>
			
			<!-- Leaflet Ajax -->
			<script src=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/ajax/dist/leaflet.ajax.js ></script>
			
			<!-- Leaflet Measument -->
			<link rel="stylesheet" href=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/measurement/leaflet-measure.css />
			<script src=/home/gabrielschubert/Documents/hawkit_app/guis/pyqt_gui/leaflet/measurement/leaflet-measure.js ></script>


            <style>
                body { margin:0; padding:0; }
                body, table, tr, td, th, div, h1, h2, input { font-family: "Calibri", "Trebuchet MS", "Ubuntu", Serif; font-size: 11pt; }
                #map { position:absolute; top:0; bottom:0; width:100%; } /* full size */
                .ctl {
                    padding: 2px 10px 2px 10px;
                    background: white;
                    background: rgba(255,255,255,0.9);
                    box-shadow: 0 0 15px rgba(0,0,0,0.2);
                    border-radius: 5px;
                    text-align: right;
                }
                .title {
                    font-size: 18pt;
                    font-weight: bold;
                }
                .src {
                    font-size: 10pt;
                }
				#delete, #export {
					position: absolute;
					top:100px;
					right:10px;
					z-index:100;
					background:white;
					color:black;
					padding:6px;
					border-radius:4px;
					font-family: 'Helvetica Neue';
					cursor: pointer;
					font-size:12px;
					text-decoration:none;
				}
				#export {
					top:130px;
				}
            </style>

        </head>
        <body>

        <div id='map'></div>
		<div id='delete'>Delete Features</div>
		<a href='#' id='export'>Export Features</a>

        <script>
        /* **** Leaflet **** */

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

        //  .. White background
        var white = L.tileLayer("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEX///+nxBvIAAAAH0lEQVQYGe3BAQ0AAADCIPunfg43YAAAAAAAAAAA5wIhAAAB9aK9BAAAAABJRU5ErkJggg==");

        // Overlay layers (TMS)
        var lyr1 = L.tileLayer('./tiles/{z}/{x}/{y}.png', {tms: true, maxZoom: 22, opacity: 0.9, attribution: ""});
        
        // Map
        var map = L.map('map', {
			measureControl: true,
            center: [-18.3604868606589, -52.694255477616245],
            zoom: 22,
            minZoom: 0,
            maxZoom: 22,
            layers: [osm]
        });
        
        lyr1.addTo(map);


        function getColor(d) {
            return d > 0.65 ? '#196619' :
                d > 0.60  ? '#248f24' :
                d > 0.55  ? '#2eb82e' :
                d > 0.50  ? '#47d147' :
                d > 0.45   ? '#85e085' :
                d > 0.40   ? '#adebad' :
                d > 0.35   ? '#d6f5d6' :
                            '#cc8033';
        }
        function style(feature) {
            return {
                fillColor: getColor(feature.properties.area),
                weight: 2,
                opacity: 0.6,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7
            };
        }

        //Geojson Layers
        
		var VECTOR_LAYERS_COUNT = 2500;
	
		for (var i = 0; i < VECTOR_LAYERS_COUNT; i++) {
			var geojsonLayer = new L.GeoJSON.AJAX("fields/data_divisions/vector"+ i.toString() +".geojson", {style: style});
			geojsonLayer.addTo(map);}
			
        
        var basemaps = {"OpenStreetMap": osm, "Without background": white}
        var overlaymaps = {"Layer 1": lyr1}

        // Title
        var title = L.control();
        title.onAdd = function(map) {
	        this._div = L.DomUtil.create('div', 'ctl title');
	        this.update();
	        return this._div;
        };
        title.update = function(props) {
	        this._div.innerHTML = "FazMaraneyRGB_transparent_mosaic_group1";
        };
        title.addTo(map);

        // Note
        var src = 'Generated by Hawkit';
        var title = L.control({position: 'bottomleft'});
        title.onAdd = function(map) {
	        this._div = L.DomUtil.create('div', 'ctl src');
	        this.update();
	        return this._div;
        };
        title.update = function(props) {
	        this._div.innerHTML = src;
        };
        title.addTo(map);
        
        var featureGroup = L.featureGroup().addTo(map);

        var drawControl = new L.Control.Draw({
            edit: {
                featureGroup: featureGroup
            }
        }).addTo(map);
        
        map.on('draw:created', function(e) {

            // Each time a feaute is created, it's added to the over arching feature group
            featureGroup.addLayer(e.layer);
        });
        
        // on click, clear all layers
        document.getElementById('delete').onclick = function(e) {
            featureGroup.clearLayers();
        }

        document.getElementById('export').onclick = function(e) {
            // Extract GeoJson from featureGroup
            var data = featureGroup.toGeoJSON();

            // Stringify the GeoJson
            var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));

            // Create export
            document.getElementById('export').setAttribute('href', 'data:' + convertedData);
            document.getElementById('export').setAttribute('download','data.geojson');
        }


        // Add base layers
        L.control.layers(basemaps, overlaymaps, {collapsed: true}).addTo(map);

        // Fit to overlay bounds (SW and NE points with (lat, lon))
        map.fitBounds([[-18.36827062251916, -52.6871074784942], [-18.35270287637126, -52.7014028427423]]);

        </script>

        </body>
        </html>

[question] consume json from Ushahidi

Hi all
I try to consume locations from a Ushahidi website which deliver a kind of "dirty" json but it passas as valid in online json validators.

I get an error at leaflet.ajax.js, row 547: SyntaxError JSON parse: unexpected end of data.

http://kajakplatser.se/json

Is there a solution for this or is Ushahidi v2.7 json inedible? :-)

Cheers
Henrik

wont work on HTTPS in chrome.

trying to see if i can use this in my project but unable to get it to work in a HTTPS environment. you can replicate the issues by going to the demo and putting an s in front of http in the address bar. happens in chrome, still works in Firefox.

have refresh clear layers directly before loading new

would it be possible to have the refresh feature on clear layers once the new data has been downloaded and about to be applied, maybe by use of the middleware function?

As it currently sits it clears the layer and a a second or more passes and the new one appears. if it was done after the data was loaded it should just be a flash and any new ones would seem to just appear.

I would write the code myself and contribute it but i am just learning javascript and even the simplest tasks at the moment are basically just trial and error for me.

Refresh on Refilter?

Hey there,

I've got refilter working, updating the properties of my Feature whenever necessary (triggered by another ajax query. However, once the data is refiltered, how does one refresh the layer? My mouseout event resets the style on the feature and updates my popup box text, but how can that be triggered by the reflier function?

I've tried running a general geojsonLayer.resetStyle() after the refilter runs, but this only works occasionally.

Any tips from anyone that's done it?

Setting style after load

Wheres the best place to set a style after the ajax load is complete

I've tried

var myStyle = {
                    color: "#FFFF00",
                    fillColor: "#FFFF00",
                    weight: 5,
                    opacity: 0.65
                };

var geojsonLayer = new L.GeoJSON.AJAX();

geojsonLayer.on('dataLoadComplete', function() {
                    geojsonLayer.setStyle(myStyle);
                }); 

map.addLayer(geojsonLayer);
geojsonLayer.setStyle(myStyle);

and it doens't seem to work, it is being called however.

If I replace the ajax call with a normal call (just loading up a static point) the style is applied correctly.

jsonp example

the jsonp example is broken because I got rid of that server.

setStyle

I would like to set the style of the layer, I was trying:

var myStyle = {color:'red', fillColor:'orange', radius: 4, apacity: 1.0, fillOpacity: 1.0, weight: 2, clickable: false};

var geojsonLayer = L.geoJson.ajax(myLayer, {style: myStyle});

Does not seem to allow for the style option?
Cheers, Ben

Can't load JSON file if local

When I use a remote JSON file it works well, but if I run something locally on my browser I get this error:
not well-formed @ file:///home/user/geo.json:1

It seems that it depends from the MIME types. See: http://stackoverflow.com/questions/677902/not-well-formed-error-in-firefox-when-loading-json-file-with-xmlhttprequest

I suppose that there could be some server with wrong or incomplete MIME types and this problem could affect those users too.

leaflet-ajax could force the file loading, regardless of the JSON file MIME type.

Load multiple files

Hello, I have multiple geojsons to add to a map. I want to load each of them one by one. But after loading all of them, I will add them to a featuregroup and then do some operations like centering the map, etc. I want to use data:loaded. It is ok if I load only one file. But I dont know how if there are multiple loads.

I found a method by jQuery: http://api.jquery.com/deferred.done/
But it does not work for Leaflet Ajax.

Any ideas?

Problem using test.geojson "external"

Hi Calvin!
I'm trying to use your library starting from https://github.com/calvinmetcalf/leaflet-ajax/blob/master/example/index.html and using the test.geojson on my pc.

My page is under http://localhost:80 and I tried to put the geojson file both under localhost:80 (apache here ...), and localhost:8080 (tomcat here .....).

The code of index,html is the same as you example, I've only changed here .....

var jsonTest = new L.GeoJSON.AJAX("test.geojson",{onEachFeature:popUp});
var jsonpTest = L.geoJson.ajax("http://localhost:8080/test.geojson",{onEachFeature:popUp,dataType:"jsonp"});

so you can replicate if you want.

I can't show the markers when active the jsonp layer: markers are ok activating the json layer. Using firebug I can see the json response but I note that I've

invalid label
{"type": "FeatureCollection", "features": [{"geometry": {"type": "Point", "coord...

referring ti the http://localhost:8080/test.geojson,

Any suggestion? Thank you very much in advance

Cesare

setRequestHeader

Hi thanks for your share,
I think it will be nice to be able to .setRequestHeader from options{requestHeaders:{ key1 : value1, key2 : value2 }...}

I will test it and maybe do my first PR :).

Unsafe eval call

Could make L.Util.JSON (window.JSON OR json2) and use it in L.Util.ajax

Would get the added benefit of having a legacy JSON.stringify impl

interact with Leaflet.markercluster

Exists an easy way for interact this plugin with Leaflet.markercluster??

1)the data is loaded in ajax
2)and the markers then are grouped by Leaflet.markercluster

Callback parameters

Hello,

I'm a beginner in Javascript, especially in Leaflet, and i have one problem with the L.GeoJSON.AJAX function. In fact, i try to generalize my style based on the layer's name. Now I have this function for my layer :

/**
 * [Execute asynchronous request and return layerContent]
 * @param  {String} layerUrl  [URL to the layer on the GeoServer]
 * @param  {Object} southWest [SouthWest lat/lon coordinate]
 * @param  {Object} northEast [NorthEast lat/lon coordinate]
 * @param  {String} layerName [Name of the current layer]
 * @return {Object}           [the current layer object -> for the map]
 */
function gs_query(layerUrl, southWest, northEast, layerName){
  return new L.GeoJSON.AJAX(layerUrl
    +"&bbox="+southWest.X+","+southWest.Y+","
    +northEast.X+","+northEast.Y,
    {
      onEachFeature: gs_setPopup, // popup information
      style: gs_setStyle, // for line and polygon
      pointToLayer: gs_setStyle // for point
    }
  );
}

And for the gs_style function I received feature and latlng parameters, but i need my layerName from gs_query(...) function. Do you know how can i get it ?

Best Regards,
PapyPev

Refilter issue (setStyle)

Refilter doesn't seem to be functional. Firebug reports an error "a.setStyle is not a function", and the rest of my code doesn't execute. A previous closed issue went off-topic and referenced this same problem.

A partial solution is successful: hiding the filtered-out markers by setting their opacity rather than using setStyle, as mentioned here. It proves the refilter function DOES work overall, but only setting opacity you end up with still-clickable ghost markers... so not a final solution.

Ultimately the problem is indeed that setStyle doesn't work on markers, only on paths. Here's a comment that hints at this. It mentions using setIcon to change the markers instead of setStyle. I guess you would need to use a transparent dummy marker image. Then, could it be made not-clickable?

In any case, shouldn't filtered-out markers be locally tagged "hidden" somehow rather than only changing their visual properties? In my case, I'm using my JSON in other data views (e.g. list view), and I'd rather simply look for a tag "hidden" rather than scanning for opacity 0 or 1, for example.

Refresh race condition

race condition when using refresh repeatedly, IE call it once and then call it again before the first one loads.

Event on completed rendering?

I'm loading custom, ungeneralized GeoJSON tiles and want to find out the time required by leaflet to render each tile. I'm attaching a performance timer to the data:loaded event.

    geojsonTiles.on('data:loaded', function(e) {
      window.console.log(window.performance.now().toFixed(3) + " geojsonTiles :loaded ");
    });

But it seems this event is always fired after the data is loaded, of course, that's by design. After the data is loaded, the geometries get rendered by leaflet. Is there any way to find out when the rendering process is done? I was playing around with global ajaxComplete or ajaxStop events, but they are not being fired by leaflet-ajax.

Is there any way to do this correctly? Thanks.

refresh and clearLayers

Hi,
Currently the refresh function calls clearLayers and then gets the data, but is possible to call the clearLayers after the data is loaded and not before?

I'm asking this because during the refresh there is second where the map is empty of data.

Already tried changing the code but with no luck.

Thanks

Loading failed on .min version

Attempting to develop a map that uses this library. Examples found online include the following line of code

<script src="https://raw.github.com/calvinmetcalf/leaflet-ajax/master/dist/leaflet.ajax.min.JS"></script>

But when I attempt to use this link I get the following error

"Loading failed for the <script> with source:" and then the link.

Is there another minified version hosted somewhere?

Problems with data:loaded

Hi I'm using the plug-in to load GeoJSON data from a Drupal server into a leaflet map. The problem I appear to be having is with the on data:loaded event triggering before all of the data seems to have been made available.
The following is "almost" working but rather than the 200+ markers that should be present only the first 75 seem to be present when the data:loaded function is called. These 75 markers display correctly on the map in appropriate clusters.

var currentMarkers = new L.MarkerClusterGroup(cluster_options).addTo(map);

     var allSchemes =  new L.GeoJSON.AJAX("//"+domain+"/schemes/map/layer/all-schemes");`

     allSchemes.on('data:loaded', function () {
        currentMarkers.addLayer(this);
     });

If, using console.log() I output the number of layers in the allSchemes object or list the keys of the allSchemes._layers object the answer is always 75. However, if I log the object allSchemes._layer itself, then the object contains all 200+ entries I would expect. I presume that the console only populates the full _layers object to display the list of contents only when it is clicked on.

Looking at the keys given to each layer object in allSchemes._layers, there appears to be gap in the sequence after the first 75 before the 76th. (Often a gap of about 50 numbers). The remainder of the keys again run in sequence.

To confuse things further or maybe clarify things?, the map has a user interaction that allows you to filter the markers using code which effectively does the following. Here all of the 200+ markers are present and can be displayed correctly.

      currentMarkers.clearLayers();
      // Go through each marker to determine if it should be included.
      allSchemes.eachLayer(function(layer) {
          if (includeLayer(layer)) {
            currentMarkers.addLayer(layer);
          }
      });

I can only presume that when the data:loaded event is triggered all the data has not been loaded or is available in the object.

Am I doing something wrong or is there anything I could do to correct this behaviour?

Thanks.

Multiple layers from same ajax request

Hi

I'm trying to make a single ajax request to make multiple geojson layers. But I'm not understanding how to setup the requests.

This is my redundant requesting code:

var povertyLayerTracts = new L.GeoJSON.AJAX("./data/ne/us-states.json",  {
        smoothFactor: 0,
        style: getStyle,
        onEachFeature: onEachFeature
    });

    var raceLayerTracts = new L.GeoJSON.AJAX("./data/ne/us-states.json",  {
        smoothFactor: 0,
        style: getStyle2,
        onEachFeature: onEachFeature
    });

    var rLayerTracts = L.layerGroup([raceLayerTracts]),
      povertyLayerTracts = L.layerGroup([povertyLayerTracts])

Using leaflet-ajax with Rails

Discussion: Rails

Has anyone tried to get this working with Rails? I've included leaflet-ajax.js in the asset pipeline (vendor/assets/leaflet/leaflet-ajax.js) and the failure point is:

var L = global.L || require('leaflet');

Console output:

leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:1 Uncaught Error: Cannot find module 'leaflet'
    at s (leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:1)
    at leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:1
    at Object.<anonymous> (leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:387)
    at Object.4../ajax (leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:520)
    at s (leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:1)
    at e (leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:1)
    at leaflet-ajax.self-926b03b1a13f4f48082577d5eec645d52c1001d3b6014e43024670c27c78ea7e.js?body=1:1
  1. In this context, I'm not sure which "require" is being used. This article was somewhat helpful along these lines: Stackoverflow link. Is this distrib not designed to be run in a browser?

  2. Is there a "module" for leaflet that needs to included somewhere? Any number of ways of referencing leaflet.js did not seem to work. (Passing urls etc.)

I'm sure there's some basic js ignorance on my part here, but I can't imagine I'm the only one to try this. Thanks for the help!

Are variables locals ?

I think there is a problem (or a misunderstanding) with variables.
Here is a sample of code which works :

var categories = {}, category;
var overlays = {}, categoryName, categoryArray;
var geoJsonLayer = L.geoJSON(featureCollection, {
  pointToLayer: function(feature, latlng) {
    category = feature.properties.destination;
    if (category == "Museum"){
      iconic = 'noir.svg';
    }
    else {iconic = 'bleu.svg';}
    return L.marker(latlng, {
      icon: L.icon.glyph({
        iconUrl: iconic,
        prefix: '',
        glyph: feature.properties.id
      })
    })
  },
  onEachFeature: function (feature, layer) { 
    if (typeof categories[category] === "undefined") {
    categories[category] = [];
    }
      categories[category].push(layer);
  }
})
for (categoryName in categories) {
  categoryArray = categories[categoryName];
  overlays[categoryName] = L.layerGroup(categoryArray).addTo(map);
}  
L.control.layers({'Streets': positron.addTo(map)}, overlays).addTo(map);

But this is not working with the same datas of "featureCollection" contained in test.json :

var categories = {}, category;
var overlays = {}, categoryName, categoryArray;
var geoJsonLayer = L.geoJSON.AJAX('test.json", {
  pointToLayer: function(feature, latlng) {
    category = feature.properties.destination;
    if (category == "Museum"){
      iconic = 'noir.svg';
    }
    else {iconic = 'bleu.svg';}
    return L.marker(latlng, {
      icon: L.icon.glyph({
        iconUrl: iconic,
        prefix: '',
        glyph: feature.properties.id
      })
    })
  },
  onEachFeature: function (feature, layer) { 
    if (typeof categories[category] === "undefined") {
    categories[category] = [];
    }
      categories[category].push(layer);
  }
})
for (categoryName in categories) {
  categoryArray = categories[categoryName];
  overlays[categoryName] = L.layerGroup(categoryArray).addTo(map);
}  
L.control.layers({'Streets': positron.addTo(map)}, overlays).addTo(map);

Since I can see my markers when I move my loop

[...]
onEachFeature: function (feature, layer) { 
    if (typeof categories[category] === "undefined") {
    categories[category] = [];
    }
      categories[category].push(layer);
      for (categoryName in categories) {
          categoryArray = categories[categoryName];
          overlays[categoryName] = L.layerGroup(categoryArray).addTo(map);
      } 
   }
})

I guess my variables are not visible outside the function.
Note: I have used console.log(overlays); in and out the function to be sure there were markers (and control.layers) to place

characters such as é, à, è, ê, replaced by �

Hello,
I used leaflet-ajax to load a geojson file that contains names with utf-8 characters such as é, à, è, or ê.
in a leaflet popup or in the console, these characters are rendered as '�'.
However, if I write down é, à or è myself (without reading it from external geoJSON) they are displayed well. Of course I checked that the encoding was correct within the geojson file.

Is there a way to specify the encoding in ajax-leaflet and solve this issue ?
Thanks a lot

L.geoJSON.AJAX is not a constructor

How do I get this plugin to work when working with npm?
I installed leaflet & leaflet-ajax with npm, and can require leaflet using 'var L = require('leaflet');
however I do not know how to properly include this leaflet-ajax extension with it.

Can anyone point me in the right direction?
Index without using beefy:
<script src="node_modules/leaflet/dist/leaflet.js"></script> <script src="node_modules/leaflet-ajax/dist/leaflet.ajax.js"></script>

When using beefy I use var L = require('leaflet');

Along with the accessToken this is the JS code:

var map = L.map('map').setView([52.11, 6.16], 7);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accesToken}', {
    id: 'mapbox.light',
    accesToken: mapboxAccessToken
}).addTo(map);

var geojsonLayer = new L.geoJSON.AJAX("data/townships.json");
geojsonLayer.addTo(map);`

Neither options (with or without beefy) allow me to use the L.geoJSON.AJAX()

Use a custom error handler

Is there a way to use a custom error handler when the ajax call fails (e.g. server side error)? I would like to have a dedicated function call in that case to notify the user properly instead of just showing nothing on the map with a geoJSON parser error at the JS console.

How not to preload

About this: "Note that data starts to download when the layer is created NOT when it’s added to the map in order to get a head start."

Is there any way not to do this? My GeoJSON is quite large. I would prefer it to be loaded only when Leaflet Control checkbox is clicked and layer is added to the map.

Example not working

GitHub pages are served over HTTPS now, https://calvinmetcalf.github.io/leaflet-ajax/example/spin.html gives:

spin.html:12 Mixed Content: The page at 'https://calvinmetcalf.github.io/leaflet-ajax/example/spin.html' was loaded over HTTPS, but requested an insecure stylesheet 'http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css'. This request has been blocked; the content must be served over HTTPS.
spin.html:1 Mixed Content: The page at 'https://calvinmetcalf.github.io/leaflet-ajax/example/spin.html' was loaded over HTTPS, but requested an insecure script 'http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js'. This request has been blocked; the content must be served over HTTPS.
leaflet.ajax.js:506 Uncaught ReferenceError: L is not defined
leaflet.spin.js:1 Uncaught ReferenceError: L is not defined
spin.html:29 Uncaught ReferenceError: L is not defined

HTTPS-served leaflet is available at https://cdnjs.com/libraries/leaflet

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.