Leaflet: addMouseCoordinates() no longer working

Created on 13 Oct 2016  Â·  15Comments  Â·  Source: rstudio/leaflet

I'm working with leaflet in shiny using the mapview package to display coordinates of the mouse. Previously it worked. I upgraded the leaflet package and mapview to the latest versions and this function no longer works. The example function:

library(mapview)
leaflet() %>% addTiles() %>% addMouseCoordinates()

R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] raster_2.5-8 sp_1.2-3 mapview_1.2.0 leaflet_1.0.2.9003

loaded via a namespace (and not attached):
[1] Rcpp_0.12.5 magrittr_1.5 gdalUtils_2.0.1.7 munsell_0.4.3
[5] viridisLite_0.1.3 colorspace_1.2-6 lattice_0.20-33 foreach_1.4.3
[9] plyr_1.8.4 tools_3.2.3 webshot_0.3.2 rgdal_1.1-10
[13] grid_3.2.3 R.oo_1.20.0 png_0.1-7 latticeExtra_0.6-28
[17] htmltools_0.3.5 iterators_1.0.8 yaml_2.1.13 digest_0.6.9
[21] RColorBrewer_1.1-2 htmlwidgets_0.7 R.utils_2.3.0 codetools_0.2-14
[25] rsconnect_0.4.3 scales_0.4.0 R.methodsS3_1.7.1 stats4_3.2.3
[29] jsonlite_1.0 satellite_0.2.0

does not produce the expected result. Any ideas?

All 15 comments

Shouldn't this be an issue on mapview, then ? cc @tim-salabim

maybe it should, maybe not. I am not sure... The error stems from this part of onRender

map.on('mousemove', function (e) {
      lnlt.text(", txt, ");
    })

where map is earlier defined as var map = this; which worked with leaflet_1.0.2.9000 but not anymore with leaflet_1.0.2.9003. So, even if it is a mapview function it seems to be related to the leaflet upgrade.

Any thoughts, Bhaskar?

That is strange, I am using .9003 and for me this in onRender is the map object. I build mapview locally and test as well.

my sessionInfo()

R version 3.3.1 (2016-06-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.4 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=de_DE.UTF-8       
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=de_DE.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=de_DE.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] mapview_1.2.5      leaflet_1.0.2.9003

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.7         raster_2.5-8        magrittr_1.5        gdalUtils_2.0.1.7  
 [5] munsell_0.4.3       colorspace_1.2-6    viridisLite_0.1.3   lattice_0.20-33    
 [9] foreach_1.4.3       plyr_1.8.4          tools_3.3.1         webshot_0.3.2      
[13] rgdal_1.1-10        grid_3.3.1          R.oo_1.20.0         png_0.1-7          
[17] latticeExtra_0.6-28 htmltools_0.3.5     iterators_1.0.8     yaml_2.1.13        
[21] digest_0.6.10       RColorBrewer_1.1-2  htmlwidgets_0.7     R.utils_2.4.0      
[25] codetools_0.2-14    sp_1.2-3            scales_0.4.0        R.methodsS3_1.7.1  
[29] stats4_3.3.1        jsonlite_1.1        satellite_0.3.0 

Hmm I can install mapview from CRAN, but installing 1.2.5 from GH gives me

** inst
** preparing package for lazy loading
Error : object 'extract' not found whilst loading namespace 'R.utils'
ERROR: lazy loading failed for package ‘mapview’
* removing ‘/Users/user001/Library/R/3.3/library/mapview’
* restoring previous ‘/Users/user001/Library/R/3.3/library/mapview’
Error: Command failed (1)
Execution halted

In any case, could you build leaflet once again, and try this out

library(leaflet)
leaflet() %>%
htmlwidgets::onRender("function(el, t) { var myMap = this; debugger;}")

Run it and open the widget in chrome, right click 'Inspect', and reload, that should put you inside the onRender call in the debugger. Inspect whether myMap is indeed the map object or not.

FWIW I just tested this on my box, I the myMap object is indeed the map widget object.

Upon further checking I see that I've added some stuff after I incremented .9003, there's nothing specific about onRender but it wouldn't hurt to build leaflet again.

This is what I see in debugger when hovering over myMap:

:
div#htmlwidget-938ea1f5e17631975f5b.leaflet.html-widget.html-widget-static-bound.leaflet-container.leaflet-fade-anim
_controlContainer
:
div.leaflet-control-container
_controlCorners
:
Object
_handlers
:
Array[6]
_initHooksCalled
:
true
_initialCenter
:
o.LatLng
_initialTopLeftPoint
:
o.Point
_layers
:
Object
_leaflet_events
:
Object
_loaded
:
true
_mapPane
:
div.leaflet-map-pane
_onResize
:
()
_panes
:
Object
_size
:
o.Point
_sizeChanged
:
false
_tileLayersNum
:
0
_tileLayersToLoad
:
0
_tilePane
:
div.leaflet-tile-pane
_zoom
:
1
_zoomAnimated
:
true
_zoomBoundLayers
:
Object
attributionControl
:
e
boxZoom
:
e
controls
:
ControlStore
doubleClickZoom
:
e
dragging
:
e
keyboard
:
e
layerManager
:
LayerManager
leafletr
:
Object
options
:
Object
scrollWheelZoom
:
e
touchZoom
:
e
zoomControl
:
e
__proto__
:
o.Class

I've installed from GH again before that.

Then it is the map object. I don't think anything changed in 0.7.7 to break that. I'll investigate more.

Thanks Bhaskar, my JS knowledge is very very basic...

btw, the error in chrome console that

map.on('mousemove', function (e) {
      lnlt.text(", txt, ");
    })

produces is index.html:37 Uncaught TypeError: map.on is not a function

I figured it out,

https://github.com/environmentalinformaticsmarburg/mapview/blob/master/R/addMouseCoordinates.R Line 64 is

 var map = HTMLWidgets.find('#' + el.id);

That's not the correct way to get a handle to the map widget, instead save the this object to a var at the start of top function and use that.

Here's the full working code, I double checked in my env. and it works.

library(leaflet)

leaflet() %>% addTiles() %>%
htmlwidgets::onRender("
  function(el, x, data) {

  // save the map object for later use below
  var myMap = this;

  // we need a new div element because we have to handle
  // the mouseover output seperately

  function addElement () {
    // generate new div Element
    var newDiv = $(document.createElement('div'));
    // append at end of leaflet htmlwidget container
    $(el).append(newDiv);
    //provide ID and style
    newDiv.addClass('lnlt');
    newDiv.css({
      'position': 'relative',
      'bottomleft':  '0px',
      'background-color': 'rgba(255, 255, 255, 0.7)',
      'box-shadow': '0 0 2px #bbb',
      'background-clip': 'padding-box',
      'margin': '0',
      'color': '#333',
      'font': '9px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif',
    });
    return newDiv;
  }
  // check for already existing lnlt class to not duplicate
  var lnlt = $(el).find('.lnlt');
  if(!lnlt.length) {
    lnlt = addElement();

    // grab the special div we generated in the beginning
    // and put the mousmove output there
    myMap.on('mousemove', function (e) {
      lnlt.text(' Latitude: ' + (e.latlng.lat).toFixed(5) +
        ' | Longitude: ' + (e.latlng.lng).toFixed(5) +
        ' | Zoom: ' + myMap.getZoom() + ' '
      );
    })
  };
}")

That's awesome! I'll update addMouseCoordinates() accordingly (most likely tomorrow). Thanks!

Thanks all for the fix. Much appreciated.

John

Sent from my iPhone

On Oct 13, 2016, at 3:19 PM, tim-salabim [email protected] wrote:

That's awesome! I'll update addMouseCoordinates() accordingly (most likely tomorrow). Thanks!

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or mute the thread.

I've just pushed the fix to mapview develop branch. Thanks for bringing this up and providing an appropriate fix!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

prateekjoshi565 picture prateekjoshi565  Â·  3Comments

cenuno picture cenuno  Â·  4Comments

mstrimas picture mstrimas  Â·  3Comments

simon-tarr picture simon-tarr  Â·  4Comments

kent37 picture kent37  Â·  3Comments