leaflet,highlight,interactive , Interactive Choropleth Map - Highlighting - getcolor function

Interactive Choropleth Map - Highlighting - getcolor function


Tag: leaflet,highlight,interactive

I'm trying to create a map of bicycle routes which will get color from properties from geojson file. It is based on Interactive Choropleth Map. The problem I have at the moment is highlighting. This part of the code checks in geojson properties the colour of route:

function getColor(d) {
    return d == 'red' ? 'red' :
           d == 'blue' ? 'blue' :
           d == 'green' ? 'green' :
           d == 'black' ? 'black' :
           d == 'yellow' ? 'yellow' :

function style(feature) {
    return {
        weight: 2,
        opacity: 1,
        color: getColor(feature.properties.colour),
        dashArray: '3',
        fillOpacity: 0.7,


It works ok but when I try to use the same function "get color" on highlighting :

function highlightFeature(e) {
    var layer = e.target;

        weight: 5,
        color: getColor(feature.properties.colour),
        dashArray: '',
        fillOpacity: 0.7

It doesn't highlight in the colors from properties of geojson. It's probably some small problem but I'm still learning and I don't understand it. Could someone explain it and point a solution, please? Thanks very much! Here's a working example (not full working of course as I'm still learning):




In your highlightFeature method, you have the setStyle method where you're referencing feature which doesn't exist. The feature is defined in e.target.feature. So this would work:

function highlightFeature(e) {
        weight: 5,
        color: getColor(e.target.feature.properties.colour),
        dashArray: '',
        fillOpacity: 0.7

But since you're not changing the color (and the opacity) you might as well leave those out entirely, which also solves the problem :)


Serve private mapping from S3 tiles by proxying data or signing urls through heroku?

I want to store mapping tiles in a private S3 bucket. Each tile has its own URL and each set of tiles could potentially have GBs of tiles. I then want to visualise these tiles through a front end mapping client (e.g leaflet). This client pulls tiles as it needs...

Deploying R shiny app using leaflet

I would like to create a shiny map using leaflet which I can publish online do that others without R can view and interact with it. I can create a shiny app using leaflet, but when I use the 'publish' button in the popup window I get an error saying...

Highlighting specific ranges on a Graph in R

library(season) plot(CVD$yrmon, CVD$cvd, type = 'o',pch = 19,ylab = 'Number of CVD deaths per month',xlab = 'Time') if i wanted to highlight a region of the graph based on x values say from 1994-1998 how do i do this? Any thought would be appreciated Thanks....

How to move marker in Leaflet along a circle?

I am working on an application where I have a marker and a circle around it. Now I am creating another marker on the circumference of the circle which is draggable. But I only want it to be draggable on the circumference itself. var coords = [parseFloat(response.lat), parseFloat(response.long)]; terrainAnalysisMap.setView(coords, 18);...

Multi continents shown when at max zoom in leaflet - data only shown on center continent

New user to Leaflet here and I've developed a mapping application that pulls geoJSON from an Oracle db. This all works but if I zoom Leaflet all the way out where it shows multiple copies of the continent my data only shows if I zoom into the center continent. My...

How to print/display/draw a MultiPolygon GeoJSON on a Leaflet map

I'm trying to display a GeoJSON MultiPolygon object in a Leaflet map. I get it from a PostgreSQL database as a JSON and I trnasform it to a GeoJSON. I've validated de MultiPolygon object in GeoJSONLint and it's ok: But I'm not able to accomplish this in my app =(...

In leaflet, how to calculate the Pixel Distance between two LatLng object?

There is a latlng distanceTo method: http://leafletjs.com/reference.html#latlng distanceTo( <LatLng> otherLatlng ) Number Returns the distance (in meters) to the given LatLng calculated using the Haversine formula. See description on wikipedia It calculates the distance (in meters) between two LatLng. However, sometimes I needs to know how many pixels are there...

how can I reduce the digits after the decimal point to only 5 digit latitude longitude in string?

I have this string generated with terraformer-wkt using leaflet: POLYGON((-66.85271859169006 10.488056634656399,-66.85351252555847 10.486178802289459,-66.85342669487 10.485250431517958,-66.84864163398743)) I want reduce the decimal digits only 5 digit after the point . POLYGON((-66.85271 10.48805,-66.85351 10.48617,-66.85342 10.48525,-66.84864)) I saw in javascrips how reduce Convert a number into a string, keeping only 5 decimals but I dont know...

Leaflet Choropleth Map and D3 Line Graph Interference

I am trying to create a choropleth map in Leaflet with a D3 line graph. I followed this tutorial to create a choropleth map and I followed this tutorial to create a D3 line graph. When I tried to put the two of them together, the Leaflet choropleth map takes...

How to access map generated by leaflet in R

Let's say I have a code like this # Install devtools if needed if(!require(devtools)) install.packages("devtools") # view rawif-devtools.R hosted with ❤ by GitHub # Install leaflet package if(!require(leaflet)) install_github("rstudio/leaflet") library("leaflet") mymap <- leaflet() mymap <- addTiles(mymap) mymap This opens it up in Chrome with a filepath like this: file:///var/folders/8x/v2tk5zy51x51jx9jbp0m29qr0000gn/T/RtmpQaeu1E/viewhtmlf74547061f7d/index.html. Let's...

How to get ID of layer in feature group on click

I have a feature group containing several markers. And I have this code to respond to a click on any of the markers: sampleFeatureGroup.on("click", function(){ alert(this.id); // something like this }); I want to be able to get the id of the marker which is clicked on from within the...

ionic & LeafletJS set marker

I am trying to set markers to my $scope.map variable with L.marker([location.lat,location.lng]).addTo($scope.map); , but I keep getting this error: TypeError: t.addLayer is not a function at o.Marker.o.Class.extend.addTo (leaflet.js:7) at mapController.js:82 I don't know why, because I am basically doing the same as in http://leafletjs.com/examples/custom-icons.html and as it is specified in...

Leaflet map legend in R Shiny app has doesn't show colors

When I try to add a legend to a leaflet map for a leaflet map (using the Leaflet for R package) incorporated into a Shiny app, the legend does not show the colors of the color palette. Instead it only shows the colors specified for the NA values, in this...

How to highlight regions of plot with gnuplot

I'd appreciate if somebody can help with this question. I am working with a radar (or spiderweb) plot with gnuplot 5.0.0: The scale and range in all axes is the same. The numbers at and beyond 1 have a special meaning and I would like to highlight that. I am...

Where is Leaflet JS object that holds all “features” on US map?

I am working with the Leaflet US map example and I have a situation where I need to have one state already highlighted when the map page loads. The highlight code is fairly straightforward (this is directly from the map example code and works fine): function highlightFeature(e) { var layer...

D3 bar chart from geojson

Has anyone worked on programmatic D3 bar charts inside div objects? I'm developing a series of layers in a web map (leaflet) for a project and I'm struggling with this part. I understand the process of how to send a D3 object to a div which in turn is sent...

Javascript getter - why does it get called at construction?

I'm new to Javascript getters/setters, but thought to use them in my Leaflet- and browserify-based project. Got a surprise. The getter gets called at initialization, for some reason unknown to me, before the class's own initialize method (Leaflet construction callback) gets to run. This of course means members are undefined...

Leaflet Map error on jquery mobile

I'm adding a simple map on jqm. The issue I am getting in console is: GET http://a.tile.openstreetmap.org/NaN/0/0.png 404 (Not Found) JS: var map = L.map('map'); $(document).on("pageinit", function () { L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 18}).addTo(map); }) On a click function adding a Marker with: L.marker([39, -6.85]).bindPopup("test").addTo(map); map.panTo(L.latLng[39, -6.85]); Using leaflet 0.8. It seems...

Creating a button for Leaflet JS “panTo spot on map” outside of the map in Meteor

I have created a map in Meteor using Leaflet JS. The problem is, I could only get map.panTo to work inside the Template.dynamicmap.rendered area. However, this makes it so anywhere you click on the map pans to the location. This is the complete rendered area with id and access token...

How to highlight rulerformat

I want highlight the rulerformat in my .vimrc. I have set ruler set rulerformat=%55(%{strftime('%a\ %b\ %e\ %I:%M\ %p')}\ %5l,%-6(%c%V%)\ %P%) I have subsequently tried all of the following: hi rulerformat ctermbg=1 hi rulerformat ctermbg=red hi Group1 ctermbg=red "if you modify the rulerformat slightly you can try to access group 1...

Leaflet.js map has extra grey space on all sides and lets me drag infinitively

I am using Leaflet.js to generate a map with some layover information. I turned on the noWrap option so that the world does not repeat. However, there is a lot of unlimited grey on all sides. I can drag the area infinitely. Unfortunately, I need to have the drag functionality...

how change type map mapbox-leaflet

I want type of map in a map that I create. I use leaflet and mapbob, but I dont know how change the type of map. var mapboxTiles = L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-zr0njcqy/{z}/{x}/{y}.png', { attribution: '<a href="http://www.mapbox.com/about/maps/" target="_blank">Terms &amp; Feedback</a>' }); How I change the content tileLayer by one create for me? Thank...

How to draw rectangle marker in leaflet given only 1 [lat,lon] pair

I need to draw a rectangle around a point in leaflet map. the point is a [lat,lon] pair. How can I easily do that? I know its easy to draw a circle. But how can I draw a rectangle?

How to get the leaflet-control-layers-toggle icon to show with angular-leaflet-directive

Following instructions as per Layers Simple example on tut: http://tombatossals.github.io/angular-leaflet-directive/#!/examples/layers-simple Inclusion of below successfully loads on page, yet icon in top right to toggle different layers is not produced. No direction provided on repo as to ensure that it is produced. $scope.layers = { baselayers: { osm: { name: 'OpenStreetMap',...

Leaflet: Toggle GeoJSON layers with Checkboxes in custom sidebar

I have a custom sidebar sitting on top of my map. Within the sidebar are checkboxes: <label><input type="checkbox" name="points" value="addressPoints" /> COUNTY</label> I would like the map to load with none of the GeoJSON layers pre-loaded and the functionality to toggle a layer on by clicking the checkbox. Below is...

How can i draw a rectangle in leaflet map given lat long position of two points

I have been given [lat, long] position of two points in a leaflet map. I have to draw a rectangle covering those two points in such a way that one point falls in the middle of 1st width edge and the second point falls in the middle of the second...

Leaflet package in R not plotting all coordinates

I'm trying to plot using leaflet with a somewhat sizable set of coordinates (~34K latitude/longitude pairs) however, using the code below it seems that leaflet is only plotting a small portion of these: data <- read.csv("Food_inspections.csv", header = TRUE) names(data) <- tolower(names(data)) data1 <- filter(data, risk == c("Risk 1 (High)","Risk...

highlight “partial” duplicates across entire sheet in Google Sheets using conditional formatting

Im trying to highlight partial duplicates in google sheets using conditional formatting. I need to highlight duplicates across multiple columns and rows in any matching cells. so far I'm using this... =countif(INDIRECT({"C2:Z18"}),C2)>1 Which works to a degree, but it only highlights exact matches. I need to find a way to...

How to plot a marker away from another marker by 100 metres in Mapbox Leaflet?

I am trying to plot a marker using Leaflet and then another marker away from the the first one by 100 metres. Plotting a marker is easy: var marker = L.marker([0, 0]).addTo(map); But now how do I plot another marker away from this one by a 100 metres? Is there...

Custom Mapbox Geocoder Control

I felt like this would be a simple task to do a Google / StackOverflow search for, but I can't seem to find anything on the topic... Anyways, all I want to do is create my own Geocoder Search bar that works OUTSIDE of my mapbox map. For instance, take...

Leaflet slider group by year

I'm using leaflet slider - https://github.com/dwilhelm89/LeafletSlider - but I can't get the desired result, even if from the plugin description it seems it can do. I have a collection of features, geometry type is polygon, where I've inserted a property "time" as requested by the plugin. I've tried bot with...

Leaflet map sources

Is there a list for all potential map sources out there? On the sample page one can browse through four types of maps. What else is out there? http://tombatossals.github.io/angular-leaflet-directive/#!/

Leaflet-draw : Create editable layers

My objective is to have a map to which I can add markers/polygons/... These elements will be saved into an Object for saving. The drawn elements can later be edited/deleted or added to. I have successfully managed to create/edit/delete them, but when I init my map with the saved objects...

create a fake map with markers using leaflet in R

I would like to create a fake map with leafleat. The idea is to have a circle with center in 0,0 and radius 2 and show some markers inside. This is how I generate the circle (comments on how to improve the code are very welcome!) library(sp) library(leaflet) circleFun <-...

How to smoothly load 200MB data to browser for visualization?

The 200MB data is collected among 300 days, about 600kb daily. Currently I use d3.tsv to load one file containing all data, and then use setTimeout to loop through each day. But the question is to load 200MB data to client's browser, it can take a few minutes... How to...

Load GeoJSON into layer from a URL?

I'm using Mapbox 2.1 and I'm trying to build a chloropleth map from a GeoJSON source, working from this example: https://www.mapbox.com/mapbox.js/example/v1.0.0/choropleth/ However, I've fallen at the first hurdle, because my GeoJSON source is a pure GeoJSON file, not a JS file like their example. So this line doesn't work for...

gnuplot highlighting points when with lines

I have 4 points I would like to plot using gnuplot, but with lines. The problem is, I can't find how to highlight these 4 points on the drawn line. I would like for the plot to be a line through the points, but that these points are also clearly...

Only return selected geojson elements in leaflet

I have this code that get all OSM alley elements in a map and that has a button to print all elements retrieved with overpass api. Instead retrieving all elements, I would like to me able to : select multiple elements on my map by clicking on those I want...

In leaflet/mapbox, why can't I set the duration of `map.fitBounds`?

I tried this: map.fitBounds(L.polyline([L.latLng(40,9), L.latLng(1,2)]).getBounds(), { padding: [50, 50], maxZoom: 17, animate: true, duration: 10 }); I expect the animation to take 10 seconds to complete, but it completes very fast.. Does anyone have ideas about how to make the duration longer for fitBounds?...

Difficulty getting pre and code tags to scroll rather than wrap

My website is built using a static site generator I created myself, and uses Bootstrap for the layout. I'm using Highlight.js for the syntax highlighting (running server-side as part of the build process) and it's working pretty well. However, one thing has stumped me. I would like the code tags...

Leaflet: check if object is Path or Marker

I have the following code to add a GeoJSON layer to a map using Mapbox.js (which of course is built on Leaflet.js): var orgLayer = L.geoJson(boundaries, { onEachFeature: onEachFeature }); this.layerGroup.addLayer(orgLayer); function onEachFeature(feature, layer) { layer.on('click', zoomToFeature, _this); } function zoomToFeature(e) { this.map.fitBounds(e.target.getBounds()); } The problem I'm having is that...

Zoom to fit leaflet.js markers

I'm converting my site from google maps to leaflet/openstreetmap. On the site, search results show up as markers on a map. Results can have one marker, or 10, or 200. That's all fine and great. But when the results have multiple markers, I'm having trouble getting it to zoom/fit all...

Get highlighted variable -Eclipse

I am implementing an Eclipse plugin for C programmers. I can't find a way to get the variable that the user already highlited.(The user will highlight a variable in the editor and I need to know which variable it is/variable's name/location of this variable in the editor, like line number..)...

How to get all markers on Leaflet

I have a listener that will detect changes of the location of objects on databases. It will pass all the information of the object that is being changed. I want to get all markers from the current map and find the marker that is affected. Once found, update the location....

Angular-Leaflet-Directive: Set opacity of a layer

I am using the angular-leaflet-directive. Is there an option to change the opacity of a layer? With 'regular' leaflet I can use layer.setOpacity(0.5). But there seems to be no option in the angular-leaflet-directive. Edit: here is my leaflet configuration: angular.module('epic-taxi') .controller('MainController', ['$scope', function($scope) { $scope.initMap = function() { angular.extend($scope, {...

Set tooltip on custom leafletjs control.

I have made several custom buttons in Leafletjs - now I would like to add a hover-over tooltip to explain what the button does. I've tried putting a "title:" and "tooltip:" in the options but still do not see the text when I hover over the control. var load =...

In leaflet, how to detect whether a LatLng in current display area?

As I know, map.project(latlng) can return a point. However, I've no idea about how to tell whether this point is in the current display area of the map.. Does anyone have ideas about this?...

Update Leaflet marker className

I have a L.layerGroup() called var stopsLayer. I want to iterate through it when certain parameters have been set by the user and "turn on" only those that match the user's input. Turning on a marker implies it exhibiting one style versus the default. The method I have for accomplishing...

Color transition effect in Leaflet.js?

See this example: https://www.mapbox.com/ten-years-openstreetmap/ Does anyone have any ideas about this? Is it done by CSS transition or Leaflet API?...

how to change url titleLayer mapbox

I need to change my url because I want modify my view map, but I don´t know how I change this url. I want modify this: L.tileLayer('https://{s}.tiles.mapbox.com/v4/mysaqygi.m8jo7i0g/{z}/{x}/{y}.png' I use mapbox, but I don´t know how to change this url when I create my map. where do I change this? I...