Coder Social home page Coder Social logo

vue-choropleth's Introduction

vue-choropleth

Downloads Version License contributions welcome

Vue components to display a choropleth map given a certain GeoJSON and another datasource to show information from. Using Vue2Leaflet

Image of Paraguay Choropleth

How to use

For a complete example using a single-file component, check the code in the example.

For a complete example using script tags check this codepen

Make sure you have Vue2Leaflet installed and add the l-map component along with the next vue-choropleth components:

import {LMap} from 'vue2-leaflet';
import { InfoControl, ReferenceChart, ChoroplethLayer } from 'vue-choropleth'

// Register these components in the components

export default {
  name: "app",
  components: { 
    LMap,
    'l-info-control': InfoControl, 
    'l-reference-chart': ReferenceChart, 
    'l-choropleth-layer': ChoroplethLayer 
  },
  // .......your component code.........

Make sure the leaflet.css is included, either via a HTML link tag or in your vue component style

@import "~leaflet/dist/leaflet.css";

On the template:

<l-map 
  :center="[-23.752961, -57.854357]" 
  :zoom="6" 
  style="height: 500px;" 
  :options="mapOptions">
    <l-choropleth-layer 
      :data="pyDepartmentsData" 
      titleKey="department_name" 
      idKey="department_id" 
      :value="value" 
      :extraValues="extraValues" 
      geojsonIdKey="dpto" 
      :geojson="paraguayGeojson" 
      :colorScale="colorScale">
        <template slot-scope="props">
          <l-info-control 
            :item="props.currentItem" 
            :unit="props.unit" 
            title="Department" 
            placeholder="Hover over a department"/>
          <l-reference-chart 
            title="Girls school enrolment" 
            :colorScale="colorScale" 
            :min="props.min" 
            :max="props.max" 
            position="topright"/>
        </template>
    </l-choropleth-layer>
</l-map>

l-choropleth-layer Props

  • geojson: The GeoJSON object to use
  • data: Data object with the information to show on the map
  • titleKey: Property of the data object to show when you hover over a certain region of your map (e.g. state_name)
  • geojsonIdKey: Property under the properties array of the GeoJSON that serves as identifier of each region of the map.
  • idKey: Property of the data object that matches the geojsonIdKey value.
  • value: JS object with two properties, key: that maps to the data property that contains the value domain set (e.g. amount) and metric: that maps to the data property that describes the unit that you're working on (e.g. "% of students")
  • extraValues: Array of value objects that show additional information of a certain region of the map.
  • colorScale: Array of hex color codes to fill each region of the map with. At the minimum you need to specify two colors, the one to use with the lowest values and another one to use with the highest values. (e.g. ["e7d090", "de7062"]) The l-choropleth-layer component pass the this information through its default slot:
  • currentItem: Current item on focus
  • unit: metric associated with the value
  • min: The lowest value on the domain set
  • max: The highest value on the domain set
  • strokeColor: String with the color to use for each of the polygons' stroke color (in hex format). (e.g.: "e7d090"). If a value is not specified fff is used.
  • currentStrokeColor: String with the color to use for the stroke of the currently polygon that the user is hovering over. (e.g.: "e7d090"). If a value is not specified 666 is used.
  • strokeWidth: Number with the width of the stroke for each polygon. (default: 2).
  • currentStrokeWidth: Number with the width of the stroke for the currently hovered polygon. (default: 5).

As seen on the example, usually you'll pass these values to the l-info-control and l-reference-chart components.

l-info-control props

This is the current item information view.

  • item: Item to show information about
  • unit: Metric to use while displaying information
  • title: Description about what each item of the map is (e.g. "State")
  • placeholder: Placeholder text to show when no element is currently selected
  • position: Where to render the component. With values allowed here (default: "bottomleft")

l-reference-chart props

  • title: Short description to show as reference of the information described by the map (e.g. "Population density")
  • colorScale: Same prop as used on l-choropleth-layer component
  • min: The lowest value represented on the visualization
  • max: The highest value represented on the visualization
  • position: Where to render the component. With values allowed here (default: "topright")

How to install

NPM

$ npm install vue-choropleth --save

yarn

$ yarn add vue-choropleth

Live Demo

Example available here.

Build Setup

# Once you have cloned this repo, install dependencies
$ npm install

# build for development and production with minification
$ npm run build

Run demo locally

# Run demo at localhost:8080
$ npm link
$ cd examples/node-example
$ npm link vue-choropleth
$ npm install
# serve with hot reload at localhost:8080
$ npm run dev

Go to http://localhost:8080/ to see the demo

NOTE: If you make changes to the library you should run 'npm run build' again in the root folder. The dev server should detect modification and reload the demo

Web example

You'll also find an example using <script> tags included under examples/browser-example

Authors

Guillermo Peralta Scura

Thanks to the works of Mickaël Bouchaud with Vue2Leaflet

vue-choropleth's People

Contributors

spiderpug avatar voluntadpear 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

vue-choropleth's Issues

Unexpected behavior when geojsonIdKey values of string type

I'm having a problem colouring a map where the values for geojsonIdKey and the (data) idKey are strings (rather than integers).

In src/components/ChoroplethLayer.vue the assumption there is an assumption that keys are numbers, and this appears deliberate. For example I see

let itemGeoJSONID = Number(feature.properties[this.geojsonIdKey])

for instance, in:

  data() {
    return {
      currentItem: { name: "", value: 0 },
      geojsonOptions: {
        style: feature => {
          let itemGeoJSONID = Number(feature.properties[this.geojsonIdKey])
          let color = "NONE"
          const {data} = this.geojsonData
          let item = data.find(x => x[this.idKey] === itemGeoJSONID)
          if (!item) {
            return {
              color: "white",
              weight: this.strokeWidth
            }
          }
...

Because of this recasting of the geojsonIdKey as a number, the following externally sourced geojson/data combination doesn't work:
geojson structured like

geojson.features[0].properties.geojsonIdKey = "SA4101"
geojson.features[1].properties.geojsonIdKey = "SA4102"
geojson.features[2].properties.geojsonIdKey = "SA4103"
...en

and data like

[
  {idKey: "SA4101", value: 77},
  {idKey: "SA4102", value: 71},
  {idKey: "SA4103", value: 81},
  ....
]

manually replacing these keys with alternative numerical fixes the issue, but is it actually necessary to make the assumption that geojsonIdKey and idKey are numbers?

Problem with

I have an issue with the new props and got this warning:

[Vue warn]: Invalid prop: type check failed for prop "strokeColor". Expected String, got Number.
And same warning for currentStrokeColor too.

If I use a number (like 666 or 999) I got this message. It doesn't work with six-characters values.

Wondering if I use it wrong ?

Thanks

Error in beforeDestroy

When the component is destroyed:
[Vue warn]: Error in beforeDestroy hook: "TypeError: this.$parent.mapObject is undefined"

Codepen

Problem with marker icon

Hi,

I want to use vue2-leaflet & vue-choropleth at the same time in two routes and I tested it with webpack. To use customised icon, I wrote this in main.js:
import { L } from 'vue2-leaflet'; delete L.Icon.Default.prototype._getIconUrl; L.Icon.Default.mergeOptions({ iconRetinaUrl: require('./assets/hb_sd_logo.png'), iconUrl: require('./assets/hb_sd_logo.png'), // shadowUrl: require('./assets/marker-shadow.png'), iconSize: [18, 18], iconAnchor: [9,9] });
The icon can be shown locally and correctly with webpack.

However, when I was going to import vue-chororpleth by:
import { InfoControl, ReferenceChart, ChoroplethLayer } from 'vue-choropleth' and add them to components, then the icons were all gone with error message.
image

If I take out the import of vue-choropleth then it works fine again. Do you know what the problem is here?

Change stroke color

Currently polygon strokes defaults to white, and grey when mouseover. Could this be customizable?

Build issue

Good day,

I am new to vuejs and nodejs.

I download the source code from github and tried to build and got following error, could you please help me with it?

I like to use it in my new project, earlier is better.

Thanks,

Shenyi

D:\Source\vuechoropleth>node -v
v8.9.1

D:\Source\vuechoropleth>npm -v
4.6.1

D:\Source\vuechoropleth>npm install
D:\Source\vuechoropleth>npm run build

[email protected] build D:\Source\vuechoropleth
cd scripts && ./build.sh

'.' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: cd scripts && ./build.sh
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Jerry Bao\AppData\Roaming\npm-cache_logs\2018-01-08T04_52_59_617Z-debug.log

Problem with rendering maps

I'm trying to rendering a choropleth map but I'm getting following errors. Map is displayed, but not the info-control nor the reference-chart.

[Vue warn]: Error in render: "TypeError: t is undefined"

found in

---> <LChoroplethLayer>
       <LMap>
         <BrazilMap> at src/components/organisms/BrazilMap.vue
           <Home> at src/components/pages/Home.vue
             <App> at src/App.vue
               <Root>
TypeError: "t is undefined"
    getMin vue-choropleth.js:52
    min vue-choropleth.js:52
    VueJS 3
    render vue-choropleth.js:52
    VueJS 19
[Vue warn]: Error in mounted hook: "TypeError: map is undefined"

found in

---> <LInfoControl>
       <LChoroplethLayer>
         <LMap>
           <BrazilMap> at src/components/organisms/BrazilMap.vue
             <Home> at src/components/pages/Home.vue
               <App> at src/App.vue
                 <Root>

Here's the code of component:

<template>
  <div class="col">
    <l-map
      :center="[-15.435695, -53.85222]"
      :zoom="4"
      style="height: 500px;"
      :options="mapOptions"
    >
      <l-choropleth-layer
        :data="covid_data"
        titleKey="state"
        idKey="state"
        :value="value"
        :extraValues="extraValues"
        geojsonIdKey="UF_05"
        :geojson="geojson"
        :colorScale="colorScale"
      >
        <template slot-scope="props">
          <l-info-control
            :item="props.currentItem"
            :unit="props.unit"
            title="COVID-19"
          />
          <l-reference-chart
            title="Casos no COVID-19 no Brasil"
            :colorScale="colorScale"
            :min="props.min"
            :max="props.max"
            position="topright"
          />
        </template>
      </l-choropleth-layer>
    </l-map>
  </div>
</template>

<script>
import { InfoControl, ReferenceChart, ChoroplethLayer } from "vue-choropleth";
import { LMap } from "vue2-leaflet";

import geojson from "../../data/uf.json";

export default {
  name: "BrazilMap",
  props: ["covid_data"],
  components: {
    LMap,
    "l-info-control": InfoControl,
    "l-reference-chart": ReferenceChart,
    "l-choropleth-layer": ChoroplethLayer
  },
  data() {
    return {
      geojson,
      colorScale: ["e7d090", "e9ae7b", "de7062"],
      value: {
        key: "confirmed",
        metric: "casos confirmados"
      },
      extraValues: [
        {
          key: "deaths",
          metric: "mortes"
        }
      ],
      mapOptions: {
        attributionControl: false
      },
      currentStrokeColor: "3d3213"
    };
  }
};
</script>

<style>
@import "../../../node_modules/leaflet/dist/leaflet.css";

#map {
  background-color: #eee;
}
</style>

Layer not render correctly (or what is expected) when the min value is 0.

Hi,
thank you for your very helpful plugin. I have managed to install it correctly and made some tests.

However I am having a problem when the min value on the dataset is 0.

If the only values on the dataset is 0 and 100, then I get this layer.

image

If I manually edit the data and insert a let say "dummy" item with value even 0.1 then the polygons with value 100 and the dummy get colored but those with 0 get no color again.

image

If there are other values between 0 and 100, then I get this layer

image

It seems that somehow the polygons with 0 value are ignored and have no color at all.

Am I missing something? Do you have any suggestion? I believe that there must be something with the utils function but not sure. Thank you for your time.

Get data from API call

So far I am able to load data from a static file and successfully render the map. However I would like to be able to load data from an API and finally update them on an event.

I have tried this but nothing happens.

export default {
  name: "app",
  components: { 
    'v-map': Vue2Leaflet.Map,
    'v-info-control': VueChoropleth.InfoControl, 
    'v-reference-chart': VueChoropleth.ReferenceChart, 
    'v-choropleth-layer': VueChoropleth.ChoroplethLayer 
  },
  data() {
    return {
      indexData: [],
      kallikratis,
      show: true,
      colorScale: ["F90606", "0616F9", "#00FF00"],
      value: {
        key: "value",
        metric: "%"
      },
      
      mapOptions: {
        attributionControl: false
      },
    }
  },
  created(){
    axios.get("/api/mapValues?index=1").then(response => {
    console.log(response.data);
    this.indexData = response.data;    
}
);
},
}

Instead I get only the polygons without any color.

Bug in ReferenceChart before destroy

Hello,
In the beforeDestroy function of ReferenceChart and InfoControl, you wrote :

beforeDestroy() {
    if (this.parent) {
      this.parent.removeLayer(this.mapObject)
    }
 }

But the correct function to use to remove controls is actually :

      this.parent.removeControl(this.mapObject)

Because of this, those two components are still present on the map when the parent choropleth component is destroyed.

Allow adding Colorpleth map as a layer to an existing map

Hi,

I just discovered this library and I think it's really nice and elegant! My problem is that I already have
a Vue2Leaflet map and only want to add a Colorpleth map as a GeoJSON layer.
I guess it should not be too complicated to implement this as a layer + controls rather than a complete solution? I think this can be very useful!

Thanks!
Omri

Minor Issue in node-example/src/App.vue and README

Hi,

In the "How to use" section of the README and App.vue of the Node example, the Vue2Leaflet Map component is imported like this (shown below in the picture):
'v-map' : Vue2Leaflet.Map,

However, when I tried using this component (I just used the component file and separately installed all the packages), I kept getting an error about v-map being unregistered. After looking at the Vue2Leaflect documentation, I found that if I changed the line to 'v-map' : Vue2Leaflet.LMap, then the component worked. Not sure if this is due to updated packages or something else I was missing, but thought I would leave this here just in case.
vue-choropleth

Choropleth map is not fully visible in full screen map

Awesome plugin! Thanks.
Could you give me a hint how I can fix the height issue for choropleth when using full screen map?
image

Here I'm using height: 100% , but as you see choropleth is not respecting it.
<l-map :center="[-23.752961, -57.854357]" :zoom="6" :options="mapOptions" style="height: 100%; z-index: 0" >

Thanks

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.