Giter Club home page Giter Club logo

leaflet.geocsv's Introduction

Leaflet GeoCSV

English: Leaflet plugin for loading a CSV file as geoJSON layer.

Castellano: Plugin para Leaflet que permite cargar un archivo CSV como capa geoJSON.

News

  • Add WKT support for POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING and MULTIPOLYGON See test example

Why GeoCSV?

  • Ease of use: A CSV (comma-separated values) file is a simple and open file format that stores tabular data in plain-text form. Virtually all spreadsheet and database software can import/export this file format.

  • Save bandwidth: When used to display markers, GeoJSON files can be up to four times as large as a CSV file containing the same information. This plugin provides the ability to download a CSV file that is then parsed into a GeoJSON document on the client side, saving you bandwidth and reducing load times. In similar scenarios, we recommend using GeoCSV together with MarkerCluster as in the Bankia Offices Map Example.

Download

Options

GeoCSV inherits the configuration options and methods of its parent object, the GeoJSON layer, and further defines the following of its own:

  • titles: An array of field titles in the same order in which they appear within the CSV file. GeoCSV only requires the presence of two field titles, lat and lng (latitude and longitude, respectively); all others field titles are permitted, omitting spaces, capitalization, accent characters, etc. By default, titles: ['lat', 'lng', 'popup']

  • latitudeTitle: The title used for the latitude value of the feature. By default, latitudeTitle: 'lat'.

  • longitudeTitle: The title used for the longitude value of the feature. By default, longitudeTitle: 'lng'.

  • lineSeparator: The string delimiting lines within the CSV file (between each GeoJSON feature). By default, lineSeparator: '\n'.

  • fieldSeparator: The string delimiting individual fields within each feature. By default, fieldSeparator: ';'.

  • deleteDoubleQuotes: A boolean indicating if double quotes surrounding individual field values should be removed. By default, true.

  • firstLineTitles: A boolean indicating if the first line of the CSV file contains field titles. If set to false, the plugin will ignore the titles configuration option. By default, false.

  • activeWKT: A boolean indicating if the GeoCSV file use WKT mode. By default, false.

  • WKTTitle: The title used for the WKT field of the feature. By default, wkt.

Methods

  • getPropertyTitle( propertyName ): When passed a property name (string), returns the associated property title.

  • getPropertyName( propertyTitle ): When passed a property title (string), returns the associated property name.

Use

  1. Include the plugin JavaScript file after leaflet.js: <script src="leaflet.geocsv.js"></script>

  2. Create a GeoCSV layer by instantiating the class or calling L.geoCsv(). Where csvFileContents is the content of a CSV file and options is an object literal as described in the previous section: var csvLayer = L.geoCsv(csvFileContents, options);

An example, using jQuery to read a CSV file, and adding a GeoCSV layer to a map:

(function() {
  'use strict';

  var map = L.map('mapContainer');

  $.get('data.csv', function(csvContents) {
    var geoLayer = L.geoCsv(csvContents, {firstLineTitles: true, fieldSeparator: ','});
    map.addLayer(geoLayer);
  });
});

Examples

Complete examples can be found within the examples subdirectory of the repository:

¿Por qué GeoCSV?

  • Comodidad: CSV es un formato abierto muy simple para representar un conjunto de datos en forma de tabla. Cualquier hoja de cálculo, por ejemplo, puede importar/exportar fácilmente a este formato.
  • Por razones de peso: Cuando se trata de representar un conjunto grande de marcadores en un mapa, el fichero geoJSON generado puede ocupar 4 veces más que la misma información contenida en un CSV. Este plugin permite que transmitas el fichero CSV y realiza la conversión al geoJSON equivalente en el lado del cliente, ahorrando ancho de banda a tu servidor y disminuyendo el tiempo de carga de tu página. En este escenario recomendamos usarlo junto al fantástico plugin MarkerCluster. Ejemplo: Mapa de las sucursales de Bankia: GeoCSV+MarkerCluster

Descarga

  • leaflet.geocsv.js: Sólo plugin 2,4K. Menos de 1K comprimido.
  • Repositorio completo .ZIP .TAR.GZ: Incluye plugin, ejemplos y librerías utilizadas en los mismos.

Opciones

Leaflet GeoCSV hereda de GeoJSON, por lo que pueden usarse todas las opciones y métodos de la superclase. Además define las siguientes opciones propias:

  • titles: Array con los rótulos o títulos de los campos en el orden en el que aparecen en el CSV. Hay dos títulos especiales que deben aparecer siempre con el mismo nombre: 'lat' → latitud y 'lng' → longitud. El resto puede adoptar cualquier forma, admitiendo espacios, mayúsculas, tildes, etc. Por defecto ['lat', 'lng', 'popup']

  • latitudeTitle: Título del campo latitud. Por defecto latitudeTitle: 'lat'.

  • longitudeTitle: Título del campo longitud. Por defecto longitudeTitle: 'lng'.

  • lineSeparator: Carácter o cadena de caracteres que usarán para separar las líneas del archivo CSV, cada una de las features. Por defecto '\n'

  • fieldSeparator: Carácter o cadena de caracteres que usarán para separar los campos del archivo CSV. Por defecto ';'

  • deleteDoubleQuotes: Valor booleano que indica si se desea borrar las comillas que delimitan los campos del archivo CSV. Por defecto true

  • firstLineTitles: Valor booleano que indica si la primera línea del archivo CSV contiene los rótulos de los campos. Por defecto false. Si se pone a true se ignorará la opción titles.

  • activeWKT: Valor booleano que indica si el archivo GeoCSV usa el modo WKT. Por defecto, false.

  • WKTTitle: Título del campo WKT. Por defecto, wkt.

Métodos

  • getPropertyTitle( nombre_propiedad ): Devuelve el rótulo asociado al nombre de la propiedad que recibe como parámetro.
  • getPropertyName( nombre_título ): Devuelve el nombre de la propiedad asociado al título del campo que recibe como parámetro.

Uso

  1. Incluimos el plugin en nuestra página, detrás de leaflet.js:
<script src="leaflet.geocsv.js"></script>
  1. Creamos la capa GeoCSV bien instanciando la clase o utilizando el alias L.geoCsv:
var mi_geocsv = L.geoCsv (csv_string, opciones);

Las opciones son las que hemos visto en el apartado anterior. El primer parámetro es un string con el contenido del fichero CSV. Si a la hora de instanciarlo no tenemos disponibles los datos, csv_string puede valer null y cargar los datos más adelante usando el método addData. Ejemplo de carga asíncrona usando jQuery:

//...
var mi_geocsv = L.geoCsv (null, {firstLineTitles: true, fieldSeparator: ','});
//...
$.ajax ({
  type:'GET',
  dataType:'text',
  url:'datos.csv',
  error: function() {
    alert('No se pudieron cargar los datos');
  },
  success: function(csv) {
    mi_geocsv.addData(csv);
    mapa.addLayer(mi_geocsv);
  }
});

Ejemplos

En el subdirectorio example se encuentran ejemplos completos del uso del plugin:

leaflet.geocsv's People

Contributors

itbeyond avatar joker-x avatar ryan-feagin avatar sm97 avatar walesmd 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

leaflet.geocsv's Issues

comma separated file

Can I use a comma separated csv file, rather than a semicolon seprarated one ?

I'd like to use field 1,field 2

rather than

field 1;field 2

Customise Popup

I am struggling to be able to customise the popup to only show certain attributes of the CSV and different titles. Using the Bankias Example the popup currently uses the script below to pull through all of the attributes using the titles within the CSV.

var popup = '';
        for (var clave in feature.properties) {
            var title = bankias.getPropertyTitle(clave);
            popup += '<b>'+title+'</b><br />'+feature.properties[clave]+'<br /><br />';
        }
        layer.bindPopup(popup);

The issue I have is that I cannot change the titles within the CSV as they are exported from a database so I therefore need to manually change them in the script above.

Using the Bankias example would it be possible to only show the "Localidad" and "Provincia" attributes and change the titles to "locality" and "province" without having to change them in the CSV?

Error

Hello,

I downloaded the zip with Leaflet.geoCSV, then i unzip in the www folder using WAMPSERVER on my localhost, but it just show (cargando... ). How can i fix the problem?

The plugin is a great contribution, thank you.

Johny Cabrera

how to remove markers using L.geoCsv

Hi,
am using your plug-in to print markers from a CSV.
i have my markers on the map fine, now i set a filter to filter my CSV to get lines by Country it works fine except that every time i click on the filter i duplicate the Markers.

i need some help please in removing completely the Markers every time i click on my filter.
i found mapa.removeLayer(arrayOfMarkers);
The arrayOfMarkers is bankias in your example and it's note an array.
Also i debugged mapa, bankias, cluster to find where markers are store but i didn't find it.
thanks in advanced,

Conditional formatting

Great plugin! I could reproduce the popup content example without any issues.

However I was wondering if there was an easy way to setup conditional formatting?

For example, setting color: red; to one of the attributes in the popup content when a value is negative, etc.?

Thanks!

use it with [email protected]

Hi,
did you ever use it with a current version of leaflet and jquery like 3.2.1/?
I'm far from being an a experienced Javascript user, but once, one year ago, I managed to use your code for a private web application together with leaflet.polylineDecorator.js. The latest version of leaflet.polylineDecorator.js requires a current version of leaflet. So I'm lost.

If you please can test it with the latest software, it will help me with my project. I hope.

Regards
Heinz

Extension to add custom pins and link in pop up

Hello, could you help me add a couple of features to the map that are set by columns of data in the CSV file:

  1. to use custom pin markers identified in a column in the CSV file
  2. to add a custom link in the pop up box loaded from data in the CSV file
    I have this (so nearly) working!
    Thanks
    Andy

WKT problems

Try using wkt files but I can't get it to work properly. Also seems to only support one title as if you add a new text it fails in the example provided. I would like to import both points and line string and style them based on one of the values. I'm doing a drag and drop function into map to make it easy for users.

This is example of files
PointCoord;DataVersion;StreetName;StreetNumber;StreetLetter;PostalCode;PostalName POINT(14.09185 57.76831);JÖNKÖPING;HEDENSTORPSVÄGEN;350;A;55475;JÖNKÖPING POINT(14.09482 57.76919);JÖNKÖPING;KÄLLEBACKSVÄGEN;310;;55475;JÖNKÖPING POINT(14.09536 57.76993);JÖNKÖPING;KÄLLEBACKSVÄGEN;293;;55475;JÖNKÖPING

Line;DataVersion;ID;altID;Name LINESTRING(14,094941 57,901929,14,095363 57,901926,14,095364 57,901890,14,095364 57,901890,14,095363 57,901926,14,096189 57,901937,14,096174 57,901892);JÖNKÖPING;10;62;Example

This is the part of code after drag and drop

function convertToLayer(CSV) { var geoLayer = L.geoCsv(CSV, { //titles: ['Feature'], //longitudeTitle: 'lng', //latitudeTitle: 'lat', //lineSeparator: '\n', activeWKT: true, WKTTitle: 'wkt', firstLineTitles: true, fieldSeparator: ';', onEachFeature: function(feature, layer) { var popupText = ''; for(var prop in feature.properties){ if(feature.properties[prop]){ popupText += '<b>' + prop + "</b>: "+feature.properties[prop]+"<br>"; } } layer.bindPopup(popupText, { maxHeight: 128, closeButton: true, className: 'upLoad', offset: L.point(0, -20) }); layer.on('click', function() { layer.openPopup(); }); }, pointToLayer: function (feature, latlng) { var type = feature.properties.ID return L.shapeMarker(latlng, { radius: 5, fillColor: newColorFill(type), fillOpacity: 1, color: newColor(type), weight: 1, shape: 'circle' }) } }); geoLayer.addTo(map); map.fitBounds(geoLayer.getBounds());

not well formed dataset Error

Hi, i just realize that i have an error in console about our data set (CSV) within leaflet.

The data are loaded but the error remains, what to do ?
thanks

u.

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.