Giter Site home page Giter Site logo

axyjo / leaflet-rails Goto Github PK

View Code? Open in Web Editor NEW
175.0 7.0 70.0 20.68 MB

This gem provides the leaflet.js map display library for your Rails 5 application.

Home Page: https://rubygems.org/gems/leaflet-rails

License: BSD 2-Clause "Simplified" License

Ruby 100.00%

leaflet-rails's Introduction

Build Status Gem Version

Quickstart Guide

To start using the leaflet-rails gem, follow the steps below (assuming you use the default asset pipeline):

First, add the following code to your Gemfile.

gem 'leaflet-rails'

Then, run bundle install from within your project to download the necessary files. Following that, open your application-wide CSS file (app/assets/stylesheets/application.css) and add the following line as a comment:

= require leaflet

After that, open your application-wide Javascript file (typically app/assets/javascripts/application.js) and add the following line before requiring files which depend on Leaflet:

= require leaflet

At this point, you may skip the first two steps of the Leaflet Quick Start guide and start at the third step (adding the map div to a view).

Version Parity

leaflet-rails keeps version parity with the upstream leaflet.js library. Before v0.7.7 the versions were not always in sync, as noted in the table below.

leaflet-rails leaflet.js Reason
0.7.4 0.7.3 Requested in #33 because of large gap between master and rubygems.org.
0.7.5 0.7.5 leaflet.js 0.7.4 was reverted.
0.7.6 ---- Skipped to sync with upstream.
0.7.7 0.7.7 Sync version numbers with upstream.

Helpers

To get you up and running quickly, you can also use the gem's helper. To get started, add the following lines to a file called leaflet.rb in config/initializers:

Leaflet.tile_layer = "http://{s}.tile.cloudmade.com/YOUR-CLOUDMADE-API-KEY/997/256/{z}/{x}/{y}.png"
# You can also use any other tile layer here if you don't want to use Cloudmade - see http://leafletjs.com/reference.html#tilelayer for more
Leaflet.attribution = "Your attribution statement"
Leaflet.max_zoom = 18

If you are using a tile layer which requires non-default subdomains such as MapQuest-OSM Tiles, you can set the subdomains like this:

Leaflet.tile_layer = "http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png"
Leaflet.subdomains = ['otile1', 'otile2', 'otile3', 'otile4']

You will then be able to call the #map helper method in a view, and make sure that the helper method is inside an erb tag like so:

<%= map(:center => {
  :latlng => [51.52238797921441, -0.08366235665359283],
  :zoom => 18
}) %>

You can also add any number of markers like so:

map(:center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
  },
  :markers => [
    {
       :latlng => [51.52238797921441, -0.08366235665359283],
    }
  ]
)

Adding a :popup element to a marker hash will also generate a popup for a maker:

map(:center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
  },
  :markers => [
     {
       :latlng => [51.52238797921441, -0.08366235665359283],
       :popup => "Hello!"
     }
  ]
)

If you want to override the map settings you have set in the initializer, you can also add them to the helper method:

map(:center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
  },
  :tile_layer => "http://{s}.somedomain.com/somepath/{z}/{x}/{y}.png",
  :attribution => "Some other attribution text",
  :max_zoom => 4
)

If you want to have multiple maps on same page , you should add unique container_id in helper method for each map:

map(:container_id => "first_map", :center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
})

map(:container_id => "second_map", :center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
})

leaflet-rails's People

Contributors

anbublacky avatar anru avatar antonj avatar asmaloney avatar axyjo avatar carljm avatar codejosch avatar dravnic avatar ershkus avatar florianf avatar itsgreggreg avatar jacobtoye avatar jasonsanford avatar jgerigmeyer avatar jgraichen avatar jomo avatar jondewoo avatar k4 avatar kbessiere avatar mehmeta avatar mortenbekditlevsen avatar mourner avatar msaspence avatar neno-giscloud avatar pedantic-git avatar pezholio avatar reignmaker avatar samatjain avatar smadeja avatar tsiege 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

leaflet-rails's Issues

Use marker-icon.png asset path in leaflet-src.js.erb detectIconPath

    _detectIconPath: function () {
        var el = L.DomUtil.create('div',  'leaflet-default-icon-path', document.body);
        var path = L.DomUtil.getStyle(el, 'background-image') ||
                   L.DomUtil.getStyle(el, 'backgroundImage');<->// IE8

        document.body.removeChild(el);

        return path.indexOf('url') === 0 ?
            path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : '';
    }

The replace failed because is not using the asset path:
/assets/marker-icon-e5459419b2a7b6835d455dff5bca5568.png%22)marker-icon.png

map helper does not work with default subdomains

Currently the map helper does not work if not custom subdomain configuration is used. Problem is, the subdomains config option is not deleted from the options has if it is nil, hence an empty string will be passed as subdomains to L.tileLayer

Something like this is required at the top of view_helper.rb:

subdomains = options.delete[:subdomains]

Workaround: Add the default subdomains to the leaflet initializer:

Leaflet.subdomains = 'abc'

Rails should be considered dependency

Hey,

Thanks for a great gem. I ran into an issue when I tried to run the spec for another gem that depends on this:

.../gems/leaflet-rails-0.7.7/lib/leaflet-rails.rb:5:in `<module:Leaflet>': undefined method `mattr_accessor' for Leaflet:Module (NoMethodError)
	from .../gems/leaflet-rails-0.7.7/lib/leaflet-rails.rb:4:in `<top (required)>'

I see here that leaflet-rails uses mattr_accessor, which isn't a pure Ruby function since it is from Rails.

Therefore I wonder if there are any specific reason to why Rails isn't considered a dependency for leaflet-rails, or if it would be possible to add it as a dependency?

Thanks,
Klas

Can't get Tiles working.

This gem is great, thanks. I am unable to get the tiles working --I cannot seem to get a Cloudmande API key, I have tried using MapBox and can't get that working, and I have tried Mapquest and no dice either.

I am wondering if I am missing something?

Leaflet.tile_layer = "https://a.tiles.mapbox.com/v4/MapID/{z}/{x}/{y}.png"

I have my actual MapID in my code.


I also tried following this: http://developer.mapquest.com/web/documentation/plugins/leaflet/v1.0/map

Any thoughts?

Incorrect dragging in Chrome (Chromium)

I have executed 'bundle update' and new leaflet-rails gem updated.

Now in chrome (I use chromium) dragging works incorrect and works fine only after some work with map (for ex. adding polyline, popups and etc).

In firefox it works correctly.

Leaflet 1.2 released August 9, 2017

"The major reason for this release is to address an unfortunate regression in the 1.1.0 release, causing trouble with several plugins. Traditionally, Leaflet plugins has altered and added to Leaflet’s namespace (the L global), something which is no longer allowed after Leaflet was rebuilt on ES6 modules (an imported module is read-only). To preserve backwards compatibility, we have made a workaround to make the Leaflet namespace and its contents mutable again."

Zoom doesn't work as showed

<%= map(:center => {
:latlng => [51.52238797921441, -0.08366235665359283],
:zoom => 15
}) %>

This doesn't set zoom to the value but this:
<%= map(:center => {
:latlng => [51.52238797921441, -0.08366235665359283],
}, :zoom => 18) %>
Does (well at the moment the map doesn't show for some reason but at least it loads in the js)

No licence specified

leaflet-rails distributed without licence terms specified.

If you ask me, using the same licence as leaflet would be reasonable.

No vendor assets are installed/downloaded

After adding the gem to the Gemfile and executing 'bundle install' none of the vendor/assets files are placed. Thus including them in the application's CSS & JS isn't possible. Any advice?

Marker icon URL detection doesn't play nice with asset digests

I've run into a strange situation with leaflet-rails and its marker-icon.png asset that is bundled with the gem. In my app, I have included my own version of this file in my assets/images folder, which is ahead of the gem's version in Rails.application.config.assets.paths.

When I run this in production, I see the following:

http://beta.pitot.io/flights/2035

As you can hopefully see on the map, the marker appears in HTML as:

http://beta.pitot.io/assets/marker-icon-f8cd76868804022ae9aeb0e99417ccb0ced2db3a9b4e107ec44f4a43ee9a6635.png")marker-icon.png

Including the quote and the parentheses before marker-icon.png.

This doesn't appear in development without asset precompilation, and didn't previously occur before an update to the leaflet gem.

I will give you a pull request with a modified version of the gem which works nicely with the digests. You might be able to come up with a nicer version, as mine is a monkeypatch.

Marker issues using geojson

I'm running into the same marker issues in version 1.3.1 reported in #56 and #59 when using the GeoJSON helper.

My ruby looks like:

<%=
  map({
    :center => {
      :latlng => [40.6400, -73.96],
      :zoom => 15
    },
    :geojsons => [
      {geojson: @school.to_json }
    ]
  })
%>

Renders this js:

var map = L.map('map');
map.setView([40.64, -73.96], 15);
L.geoJSON({"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-74.01176589685977,40.64915359571094]},"properties":{"id":1,"ats_code":"15K001","borough":"K","borough_number":"2","loc_code":"K001","name":"P.S. 001 THE BERGEN","school_type":"Elementary","managed_by":"1","geo_district":"15","admin_district":"15","address":"309 47 STREET","city":"BROOKLYN","state_code":"NY","zip":"11220","principal":"Jennifer Eusanio","principal_phone":"718-567-7661","fax":"718-567-9771","grades":"PK,0K,01,02,03,04,05,SE","created_at":"2018-02-04T15:37:37.840Z","updated_at":"2018-02-05T01:58:28.979Z"}}]}).addTo(map);
L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/{z}/{x}/{y}?access_token={my_access_token}', {
attribution: 'attribution',
maxZoom: 18,
}).addTo(map);

which attempts to load these urls:

  • http://localhost:3000/assets/marker-icon-574c3a5cca85f4114085b6841596d62f00d7c892c7b03f28cbfa301deb1dc437.png%22)marker-icon-2x.png
  • http://localhost:3000/assets/marker-icon-574c3a5cca85f4114085b6841596d62f00d7c892c7b03f28cbfa301deb1dc437.png%22)marker-shadow.png

The leaflet-self.js file loads successfully and looks like:

L.Icon.Default = L.Icon.Default.extend({
  _getIconUrl: function (name) {
    var paths = {"icon-2x.png":"/assets/marker-icon-2x-00179c4c1ee830d3a108412ae0d294f55776cfeb085c60129a39aa6fc4ae2528.png","shadow.png":"/assets/marker-shadow-264f5c640339f042dd729062cfc04c17f8ea0f29882b538e3848ed8f10edb4da.png","icon.png":"/assets/marker-icon-574c3a5cca85f4114085b6841596d62f00d7c892c7b03f28cbfa301deb1dc437.png"};
    return paths[name + '.png'];
  },

  _detectIconPath: function () {
    return '';
  }
});
L.Marker = L.Marker.extend({
  options: {
    icon: new L.Icon.Default()
  }
});

L.marker = function(latlng, options) {
  return new L.Marker(latlng, options);
}

Any idea what might be wrong in my case?

Version Parity

The Readme in the Version Parity section could be interpreted to mean that leaflet-rails is up to v0.7.7. But you're current so the section should mention that.
Maybe a line at the top could be change to: leaflet-rails tries to keep version parity with leaflet.js and currently at Leaflet 1.4. However in the past version parity was not always possible. Discrepancies have been noted below.

Or even better the whole section could be:
leaflet-rails keeps version parity with leaflet.js and currently at Leaflet 1.4. Before v0.7.7 the versions were not always in sync.

I don't know if you even need the last sentence.

Add collection of markers

Hi. Il love this gem but have a few problems.
I have a object that contains a collection of coordinate. How can I do to pass this object to render many markers on tje the same map

map(:center => {
:latlng => [51.52238797921441, -0.08366235665359283],
:zoom => 18
},
:markers => [
<% @coordinate.each do |item| %>
{
:latlng => [<%=item.lon%>,<%= item.lat%>],
}
<% end %>
]
)

Thank for help

Update to latest leaflet

Please consider to update leaflet-rails to upstream version 0.4.4, it has number of regressions fixed.

Can't create initializer

Hi! With help of your guide, i just added leatflet-rails gem to my Gemfile, and than tried to create initializer for this gem(just touch config/initializers/leatflet.rb), tried to put this strings into it

Leaflet.tile_layer = "http://{s}.tile.cloudmade.com/YOUR-CLOUDMADE-API-KEY/997/256/{z}/{x}/{y}.png"
# You can also use any other tile layer here if you don't want to use Cloudmade - see http://leafletjs.com/reference.html#tilelayer for more
Leaflet.attribution = "Your attribution statement"
Leaflet.max_zoom = 18

But when i started my server, i got an exception from this file:
Uninitialized constant Leatflet
Will be glad if you will answer fast!
Rails v.: 5.1.0

Support For MarkerClusters

Currently I can't add marker clusters if I add the map and markers using the helper. Would be good to have a way to do that.

Error: No value provided for variable {s} with layers providers with a tile layer with {s}

Hi,
I have a working example on a page that displays a map with leaflet-rails 0.7.7 and rails 4.2.6
my stylesheets/application.css
#map { height: 450px; }

my javascripts/application..js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require leaflet
//= require_tree .

my views/routes/show.html.erb
<%= map(:center => { :latlng => [51.52238797921441, -0.08366235665359283], :zoom => 12 }) %>

my config/initializers/leaflet.rb:
Leaflet.tile_layer = 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png' Leaflet.attribution = 'Tiles courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a>' Leaflet.max_zoom = 18

As I say it works.
But when I change the Leaflet.tile_layer to the one that appears in the Leaflef examples, ie:
Leaflet.tile_layer = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png I get the error and if I change it to Leaflet.tile_layer = 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png' (also from the leaflets examples) I also get the same error.
How can i fix the reference to that s variable?

Marker gone in development mode

I updated the leaflet gem from 0.7.7 to 1.0.2
In development my map markers are not found anymore.

The system does a get /assets/marker-icon-[lot of number].png%22marker-icon.png

I think it appends "%22marker-icon.png" it is a very strange filename

When i downgraded to 0.7.7 things worked ok again. When i updated to 1.0.2 markers where gone again !!

I am working on Window, perhaps this has something to do with it.

Vector layers support

It would be great to have the support in the helper for vector layers (circles, polygons, etc)

License missing from gemspec

Some companies will only use gems with a certain license.
The canonical and easy way to check is via the gemspec
via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

There is even a License Finder to help companies ensure all gems they use
meet their licensing needs. This tool depends on license information being available in the gemspec.
Including a license in your gemspec is a good practice, in any case.

How did I find you?

I'm using a script to collect stats on gems, originally looking for download data, but decided to collect licenses too,
and make issues for missing ones as a public service :)
https://gist.github.com/bf4/5952053#file-license_issue-rb-L13 So far it's going pretty well

Map option scrollWheelZoom doesn't work.

I defined my map this way:

<%= map(:container_id => "map-canvas",
:scrollWheelZoom => :false,
:center => {
:latlng => [46.203, 6.142],
:zoom => 14
},
:markers => @markerslist
) %>

but the code is rendered this way:

L.tileLayer('https://api.tiles.mapbox.com/v4/{...}/{z}/{x}/{y}.png?access_token={...}', {
attribution: 'MapBox',
maxZoom: 18,
scrollWheelZoom: 'false',
subdomains: '',
}).addTo(map)

If I remove the quotes around 'false', then the option is taken into account.

In lib/leaflet-rails/view_helpers.rb line 81, I see the quotes are added to each option.
How would it be possible to workaround this?

Better changelog or releases/tags

We're upgrading from 0.7 to 1.2 and it's very difficult to understand what has changed without looking directly at commits. Please help the OSS world by either updating the changelog or having helpful notes attached to tags/releases.

Adding Uniq container_id in leaflet-rails helper

If you want to have multiple maps on same page , you should add unique container_id in helper method for each map:

map(:container_id => "first_map", :center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
})

map(:container_id => "second_map", :center => {
    :latlng => [51.52238797921441, -0.08366235665359283],
    :zoom => 18
})

my question is how can i do to adding a uniq _container_id in leaflet.rb file in initializes folder.

thanks

Leaflet 1.6 released

Leaflet 1.6 was published on Nov 17, 2019. Could you please update leaflet-rails from Leaflet 1.5.1 to 1.6?

Bootstrap compatability

I'm having an issue when I embed a leaflet map via leaflet-rails into a bootstrap nav box; specifically a nav-tabs box.

Here's the relevant docs for the bootstrap stuff.
http://getbootstrap.com/2.3.2/components.html#navs

The issue I'm seeing is that some of the tiles aren't rendering. It kinda seems like leaflet thinks the location that should be rendered is different than what can be seen through the viewport. (ie: it's rendering tiles to the left of the viewport)

why js asset file extension is ERB

Hi axyjo!

It might be a stupid question but, why is your leaflet.js file an erb? I didn't see what you inject in.

It's actually annoying for my IDE that doesn't recognize the Leaflet.js.erb as a JS file and thus doesn't load it as an external lib. Then I have no auto-completion...etc

Do you think it would be a problem to rename it to leaflet.js?

Many thanks for the gem btw =)

Paul

generate leaflet image as .png/.jpg

Hi,

I would like to create leaflet image as .png/.jpg for the given latlng.

How to do it ?

Edit: I want it to happen in backend rather client side driven ?

Thanks,
Kiran.

ReferenceError: L is not defined

Hi, sorry for writing an issue for this, but I can't get any further...maybe it's really simple.

I followed your README, installed the leaflet-rails gem, added the "require" statements in application.css and application.js, added the leaflet.rb in initializers, and also added the depend_on_assets tags in application.css because I am using rails 4.1.4.
I created a map view, and the only content is the helper method:

<%= map(:center => {
:latlng => [51.52238797921441, -0.08366235665359283],
:zoom => 18
}) %>

I always get "ReferenceError: L is not defined" in the browser...what could I be missing? In the browser inspection, I can see the leaflet.js being referenced as "/assets/leaflet.js" and that file exists there for that URL. Looking further, I can see that sprockets adds all javascript includes at the end of the file, but the helper generates a script before that in the middle of the page where the map div is....

Any suggestion?

fitbounds padding not working

Hello,
the fitbounds output are not considering the padding parameter.

I defined my map like this:

<%=
          map(:container_id => "mapid",
            :markers => markers,
            :fitbounds => bounds
          )
        %>

where bounds are my [] of latlng. it work very well like this but
I tried to use the padding parameter, and didn't work so we had to use em script tag after that

<!--script feito devido a falta de compatibilidade da gem para receber padding em fitbounds -->
      <script type="text/javascript">
        map.fitBounds(L.latLngBounds(<%= bounds %>), { padding: [50,50] });
      </script>

Example code

Is there any example code or completed Rails demo application using this gem?

rubygems.org not up to date

Could you push this to rubygems again?
#31 isn't included there, so you get

undefined method `subdomains=' for Leaflet:Module (NoMethodError)

when you use the rubygems.org version.


for anyone else having this problem, you can use this in your Gemfile as a workaround:

gem 'leaflet-rails', github: "axyjo/leaflet-rails"

Leaflet 1.4 released

There is new version of Leaflet (1.4) available and leaflet-rails is now a version behind.

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.