Git Product home page Git Product logo

leaflet-layerjson's Introduction

Leaflet JSON Layer

npm version

Simple way for transform any JSON data source in a Leaflet Layer!

A Dynamic Leaflet Layer that load JSON data in layer in the form of markers with attributes

and minimize remote requests with caching system

Copyright 2023 Stefano Cudini

If this project helped your work help me to keep this alive by Paypal DONATION ❤

Tested in Leaflet 0.7 and 1.1

Options

Option Data Description
url String remote url
jsonpParam String callback parameter name for jsonp request append to url
jsonpParam String callback parameter name for jsonp request append to url
callData Function custom function for data source, params: (req: url
Filtering
propertyItems String json property used contains data items
propertyLoc String json property used as Latlng of marker, if is array: ['lat','lon'] select double fields
locAsGeoJSON String interpret location data as [lon, lat] value pair instead of [lat, lon]
propertyTitle String json property used as title in marker
filterData Function function for pre-filter data
Rendering
dataToMarker Function function that will be used for creating markers from json points
layerTarget L.Layer pre-existing layer to add markers(L.LayerGroup, L.MarkerClusterGroup)
buildPopup Function function popup builder
optsPopup String popup options
buildIcon Function function icon builder
Caching
minZoom Number min zoom for call data
caching Boolean remote requests caching
cacheId Function function to generate id used to uniquely identify data items in cache
minShift Number min shift for update data(in meters)
precision Number number of digit send to server for lat,lng precision
updateOutBounds String request new data only if current bounds higher than last bounds
updateMarkers Boolean update all markers in map to last results of callData

Events

Event Data Description
'dataloading' {req: url bbox}
'dataloaded' {data: json} fired on ajax/jsonp request success

Usage

var l = new L.LayerJSON({url: "search.php?lat1={lat1}&lat2={lat2}&lon1={lon1}&lon2={lon2}" });
map.addLayer(l);

Where

Demos:

https://opengeo.tech/maps/leaflet-layerjson

Source:

Github

Atmosphere

Build

This plugin support Grunt for building process. Therefore the deployment require NPM installed in your system.

After you've made sure to have npm working, run this in command line:

npm install
grunt

leaflet-layerjson's People

Contributors

jpochyla avatar skakri avatar stefanocudini avatar thomasg77 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

leaflet-layerjson's Issues

Markers diseappearing on zoom in/out when updateOutBounds is set to true

Hello Stefano Cudini,
It seems that there is a bug with markers: they disappear on zoom in/out when falling out of zoom bounds, you have to uncheck/check the layer to get the markers back. I only noticed the issue once implemented locally, sigh... :)
Visible on your examples too if I except "Data by Callback".

The bug disappear if I set updateOutBounds to false.

Best regards and thank you for the script!

function icon builder

How can I add a custom icon using buildIcon? And why do the icons disappear when I define $data['icon']='myIcon'?

OVERPASS API - Visualize way center

Using overpass API I want to see also a way using the center function:

L.layerJSON({url: 'http://overpass-api.de/api/interpreter?data=[out:json];(way({lat1},{lon1},{lat2},{lon2})[tourism=alpine_hut];);out center;',

        propertyItems: 'elements',
        propertyTitle: 'tags.name',
        propertyLoc: ['center.lat','center.lon'],

...

but it doesn't work

it produce an element Latlng (NaN,Nan)

Why?

Thanks in advanced
R

ps:

output json seems correct:
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2014-08-20T13:00:01Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "way",
"id": 103839515,
"center": {
"lat": 44.7271834,
"lon": 9.0168653
},
"nodes": [
1198725685,
1198724829,
1198725506,
1198725193,
1198725685
],
"tags": {
"building": "yes",
"name": "Bivacco Alda e Carla Merchesotti",
"operator": "Club Alpino Italiano - sezione di Novi Ligure",
"tourism": "alpine_hut"
}
},
{
"type": "way",
"id": 149158829,
"center": {
"lat": 44.4972211,
"lon": 8.4904252
},
"nodes": [
1621763986,
1621764012,
1621763996,
1621763974,
1621763987,
1621764003,
1621763986
],
"tags": {
"building": "yes",
"name": "Rifugio Sciverna",
"tourism": "alpine_hut",
"website": "http://www.rifugiosciverna.com"
}
},
{
"type": "way",
"id": 293034542,
"center": {
"lat": 44.7266464,
"lon": 9.1099179
},
"nodes": [
2965883248,
2965883247,
2965883250,
2965883253,
2965883252,
2965883251,
2965883248
],
"tags": {
"building": "yes",
"name": "Rifugio Piani di San Lorenzo",
"tourism": "alpine_hut"
}
}

]
}

'async: false' and console warning

Hi, @stefanocudini.

First, thank you for this very useful Leaflet plugin.

Leaflet Dynamic JSON Layer README's says:

callData alternative function that return data (if use $.ajax() set async=false)

This advice produces the expected result on callData(), which is to retrieve an arbitrary JSON from an arbitrary endpoint so L.layerJSON() render its markers correctly.

But according to XHR Living Standard:

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when entry settings object's global object is a Window object. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs.

This is exactly what modern browsers do. Take Chromium 53 for instance, when dynamically loading a JSON with jQuery.ajax(url, {async: false}), it throws at the console:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

When async: true, there are no donuts for markers though. The data required isn't there yet when L.layerJSON() is fired, so it has nothing to show. In that case, the JSON data is loaded asynchronously at some arbitrary moment after window.onload().

We are still some years away from the day where this call is going to be promoted from a warning at the console to 'an InvalidAccessError exception'. So maybe the time to have a closer look into it has arrived.

Is there any possibility that you could improve callData() so it can deal with async: true?

Deprecated include of L.Mixin.Events: this property will be removed in future releases...

I've got this error message in Chrome, using Leaflet v1.1.0:

Deprecated include of L.Mixin.Events: this property will be removed in future releases, please inherit from L.Evented instead. Error
at y (mydomain.com...)
at Function.v.extend (mydomain.com...)
at http://terkep.futonaptar.info/js/leaflet-layerjson.min.js:17:40
at http://terkep.futonaptar.info/js/leaflet-layerjson.min.js:17:5735

Is it possible to ugrade the plugin somehow?

Thanks in advance!

What about polygons?

I have geojson that return polygons, like:

{ 
    "type": "FeatureCollection", 
    "features": [ 
        {
            "type": "Feature", 
            "geometry": {
                "type":"Polygon",
                "coordinates":[[[19.011786843804092,-33.653375433463729],[19.011769373600742,-33.653349976975719],[19.011758205302748,-33.653322172557736],[19.011753768101549,-33.653293088716289],[19.011756232516287,-33.653263843126368],[19.011765503840888,-33.653235559679977],[19.011781225783547,-33.653209325295592],[19.011802794158836,-33.653186148148144],[19.011829380106171,-33.653166918925265],[19.011859961942516,-33.653152376598015],[19.011893364425049,-33.653143080022403],[19.011928303915099,-33.653139386462314],[19.011963437707649,-33.653141437859937],[19.01199741563077,-33.653149155380788],[19.012028931931923,-33.653162242443429],[19.012056775457324,-33.65318019611707],[19.012079876195923,-33.653202326449289],[19.012218836195935,-33.65336531661319],[19.012236306399284,-33.653390773096675],[19.012247474697276,-33.653418577492495],[19.012251911898478,-33.653447661291523],[19.012249447483743,-33.653476906818987],[19.012240176159139,-33.65350519018606],[19.012224454216479,-33.653531424480278],[19.012202885841194,-33.653554601534722],[19.012176299893856,-33.653573830671014],[19.012145718057514,-33.65358837292704],[19.012112315574978,-33.653597669454541],[19.012077376084928,-33.653601362994955],[19.012042242292377,-33.653599311608303],[19.012008264369261,-33.653591594127811],[19.011976748068104,-33.653578507130455],[19.011948904542699,-33.653560553539918],[19.011925803804104,-33.653538423299807],[19.011786843804092,-33.653375433463729]]]
            }, 
            "properties": {
                "erven_id":"7141412",
                "ervenlines_id":"46784835"
            }
        }
    ]
}

I see in all your examples that you only work with points (markers). How will I handle Polygons, Multipolygons, LineStrings, MultiLineStrings, etc?

local file?

Hey Stefano, great script, works great with an external source. But how about a local file? When I manually download the file(json) from the api and store it locally I can't seem to load it using url or callData methods?
Thanks!

jsonp request

Hi there,

Im trying to pass some json however I am gtting the following error in my console
Uncaught SyntaxError: Unexpected token :

It's weird, above the console I am seeing the json result, however the makers are not drawing on the map. This is what Im using

var jsonLayer = new L.LayerJSON({
                        url: 'http://biocache.ala.org.au/ws/occurrences/search?q=genus:Macropus',
                        jsonpParam: 'json_callback',
                        propertyItems :'occurrences',
                        propertyLoc: ['decimalLatitude','decimalLongitude'],
                        propertyTitle: 'occurrences'
                    });
    map.addLayer(jsonLayer);

I'm not sure if Im doing something wrong or if its a plugin thing. Any suggestions?
Thanks,
Rowan

use debounce function on map moveend zoomend

        function debouncer(func, timeout) {
            var timeoutID;
            timeout = timeout || 300;
            return function () {
                var scope = this , args = arguments;
                clearTimeout( timeoutID );
                timeoutID = setTimeout( function () {
                    func.apply( scope , Array.prototype.slice.call( args ) );
                }, timeout);
            };
        }

Lines and Polygons with layerJSON

Hi Stefano

First of all, thank you for sharing your very useful plugins for leaflet.

I would like to know, if it's possible to get lines and polygons as a layer, when using leaflet-layerJSON?

I have tried the following script, but doesn't get any railways as a layer.

        var way = L.layerJSON({
            url: 'http://overpass-api.de/api/interpreter?data=[out:json];way({lat1},{lon1},{lat2},{lon2})[Key:railway];out;',
            propertyItems: 'elements',
            propertyTitle: 'tags.name',
            propertyLoc: ['lat','lon'],
            buildPopup: function(data, marker) {
                return data.tags.name || null;
            }
        }).addTo(map);

I'm new to coding and webmapping and apologize if my question is unclear or if it is posted in a wrong section.

Anders

JSON syntax compatibility

Ciao Stefano,

I try to use your plugin to display the data from the UNHCR (Refugee Agency) with leaflet. They share the location of the displaced people around the world with an API in JSON here :

http://data.unhcr.org/wiki/index.php/Get-population-settlements

I took example on the Overpass API example you give here : http://labs.easyblog.it/maps/leaflet-layerjson/examples/overpass.html but so far I didn't manage to make it work.

I'm wondering if this is because of the syntax of the JSON. The Overpass API gives an JSON that looks like that :

{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2014-11-12T14:32:02Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [ ....

The UNHCR API JSON file directly starts with the data :

[
{
"name": "PTP Ref. Camp",
"country": "Liberia",
"region": "Grand Gedeh",
"population": [
{
"module_name": [
{
"EN": "Registered Refugee Population"
},
{
"FR": "Données démographiques concernant la population affectée"
}
],
"module_type": "Total Population & Demogrpahy",
"url": "http://data.unhcr.org/liberia/settlement.php?id=30&country=119&region=22",
"value": "15379",
"households": "5018",
"demography": {
"04M": "1276",
"04F": "1312",
"511M": "1847",
"511F": "1772",
"1217M": "1056",
"1217F": "826",
"1859M": "3293",
"1859F": "3459",
"60M": "220",
"60F": "318"
},
"updated_at": "2014-04-30 03:35:08"
}
],
"latitude": "6.067023000",
"longitude": "-8.139816000",
"instance_id": "liberia"
},

The code in the example you gave is :

var data = L.layerJSON({
url: 'http://overpass-api.de/api/interpreter?data=[out:json];node({lat1},{lon1},{lat2},{lon2})[amenity=bar];out;',
propertyItems: 'elements',
propertyTitle: 'tags.name',
propertyLoc: ['lat','lon'],
buildPopup: function(data, marker) {
return data.tags.name || null;
}
}).addTo(map)

I tried to adapt like this:

var sett = L.layerJSON({
url: 'http://data.unhcr.org/api/population/settlements.json',
propertyTitle: 'name',
propertyLoc: ['latitude','longitude'],
}
}).addTo(map);

But it doesn't work.

So my question:

Is it possible to use your plugin with a JSON file written like the UNHCR's one ? (without the "element" item ?)

Thank you in advance for your answer,

Cheers from France,

Leo

caching: true & zoomOut is not realoding data

When i tried turn off caching, markers and clusters are blinking. So i decided to set caching on true which seems to work fine on dragging but had an issue on Zoom Out event when is necessary to get new data.

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.