Quantcast
Channel: Question and Answer » leaflet
Viewing all 198 articles
Browse latest View live

In Leaflet how to use control on an existing div?

$
0
0

In Leaflet, adding control classes like Zoom In/Zoom Out is possible. But I do not want to add a new div into my html. I want to use an existing div to contain my tools. I am pretty sure that it can be done by using onAdd method;

onAdd: function (map) {

    container = CALL MY OWN DIV ITEM

    this._map = map;

    this._zoomInButton  = CALL ITEM NO 1 FROM CONTAINER AND ADD `this_zoomIn` FUNCTION
    this._zoomOutButton = CALL ITEM NO 2 FROM CONTAINER  AND ADD `this_zoomOut` FUNCTION

    this._updateDisabled();
    map.on('zoomend zoomlevelschange', this._updateDisabled, this);

    return container;
},

Is this possible? I know that in case of zoom in/zoom out I can simply use map.zoomIn(1) command, but I want to call more sophisticated control structures. This is why I need this.

I also tried converting all the methods in control class to functions in order to call them with jquery but I failed to do so.


Disable leaflet layer check box in a layer control w/ zoom

$
0
0

I would like to have layers listed in my layer control, but have their check boxes disabled when zoomed out beyond a certain level.

I am asking the same question that is found here, but with Leaflet instead of OpenLayers.

This is admittedly a “has this already been done” question. I could try to figure out if it can be translated easily from the open layers example above, but maybe someone has accomplished this already?

Cartodb add basemap switcher

$
0
0

I currently have a map created entirely in the CartoDB editor, including custom map. For some reason it doesn’t allow you to add an attribution in the editor but thats a different problem.

So my map has a custom baselayer and 3 toggleable layers. Here is the code.

<script>
  function main() {
    cartodb.createVis('map', 'https://paulm.cartodb.com/api/v2/viz/5fd91fc8/viz.json', {
    })
    .done(function(vis, layers) {
      window.layers = layers;
    })
    .error(function(err) {
      console.log(err);
    });
  }
  window.onload = main;
</script>

I know that I could replace the current base map by adding

.done(function(vis, layers) {
  var basemap = layers[0];
  basemap.setUrl('http://{s}.tile.osm.org/{z}/{x}/{y}.png');
})

However im not sure if its possible to enable a base map switcher, or if I need to add it as a new layer completely will I need to do that via the code. Adding in a whole new set of tiles seems to be more of a basemap switch than just a data layer.

Leaflet popup options with geoJSON data

$
0
0

In the following how would I customize the popup options? I want to add in the option for the keepInView to be true.

var myLayer = L.geoJson(polygon, {
onEachFeature: yourOnEachFeatureFunction
}).addTo(map);

function yourOnEachFeatureFunction(feature, layer){
if (feature.properties.name) {
layer.bindPopup(feature.properties.name);
}
}

Lat long co-ordinates in geojson format for Alaska(smaller), bigger Guam and Puerto Rico?

$
0
0

How do I get the geojson format of Alaska, Guam and Puerto Rico in different sizes ? The sizes I have for Alaska is too large and too small for Guam and Puerto Rico. I’m very new to mapping technologies. So I’m not aware of any tools that will allow me to resize these polygons to put it on my map.It would be great if somebody could point me where I could find the rescaled version (in geo Json) of these states. Also it would be awesome if someone could point me to simple tools to that would allow me to resize the co-ordinates(in geojson format)I have for these states.

Update: the sizes of Guam and Puerto Rico in the current zoom level of my map is so tiny, it’s virtually impossible to launch a pop up on clicking those states.

enter image description here

switching the layers on/off in leaflet map layer tree based on styling

$
0
0

I am developing web application which has leaflet maps. I need the layer control which is similar to QGIS

layer control

I am using Geoserver to get the layer as wms format and I added that layer using tilelayer.wms function. I am using jstree plugin for tree like structure of layers. So when user checks any layer I added that layer using map.addLayer() function. When user unchecks the layer I used map.removeLayer() function.
So now question is I want to add or remove the layer based on it’s style like this

enter image description here

How to achieve this functionality using leaflet and geoserver and jstree.

Leaflet Vector Layers Not Rendering During FlyTo Animation

$
0
0

In version 1.0 of Leaflet, when using the FlyTo function as per this JSFiddle, is it possible to force vectors to render/ draw as the animation is happening?

My current issue is when using the marker.cluster function, the animation starts and then none of the points display as you would expect until the animation ends.

I believe the issue is like this OpenLayers question, is there a similar solution for Leaflet?

UPDATE: It appears the issue is related predominately to GeoJSON layers, see this first example that animates well and then this example that uses a GeoJSON layer and the animation doesn’t render the vector.

How do I show feature attributes in a Leaflet popup?

$
0
0

So I have a JSON file displayed on my leaflet webmap. I would like to have it so a popup will appear when a feature is clicked. Right now it is a polygon feature. How do I call up information from the JSON file (Syriashape.json) so it can be displayed? The fields I would like to display are called “Sheet_Num” and “Date”

Currently, this is what I have:

// load GeoJSON from an external file
$.getJSON("Syriashape.json",function(data){
  // add GeoJSON layer to the map once the file is loaded
  L.geoJson(data).addTo(map).bindPopup("Attributes Popup Here");
});

Combining two leaflet plugins

$
0
0

I am new to leaflet (but I used leaflet with R) and javascript. I have discovered two great leaflet plugins, Leaflet.Elevation and leaflet-gpx. I managed to make them work individually, but I was wondering if they could be both combined in one map. I tried but I failed miserably. Maybe I could use Leaflet.Sync but I was wondering if someone could point me in the right direction (if possible).

here is what I have so far. The first big part of the code is working, it the last past part of the code (starting at var el = L.control.elevation();) that I can’t make work

<head>
<title>leaflet-gpx demo</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" />
<link rel="stylesheet" href="../dist/leaflet.elevation-0.0.4.css" />

<style type="text/css">
  body { width: 1100px; margin: 0 auto; }
  .gpx { border: 5px #aaa solid; border-radius: 5px;
    box-shadow: 0 0 3px 3px #ccc;
    width: 1100px; height: 550px;, margin: 0; }
  .gpx header { padding: 0.5em; }
  .gpx h4 { margin: 0; padding: 0; font-weight: bold; }
   .gpx .start { font-size: smaller; color: #444; }
  .gpx .map { border: 1px #888 solid; border-left: none; border-right: none;
    width: 1100px; height: 430px; margin: 0; }
  .gpx footer { background: #f0f0f0; padding: 0.5em; }
  .gpx ul.info { list-style: none; margin: 0; padding: 0; font-size: smaller;}
  .gpx ul.info li { color: #666; padding: 2px; display: inline; }
  .gpx ul.info li span { color: black; }
</style>
</head>


<body>
  <article>
    <div class="map" id="demo-map"></div>
  </article>

  <footer>
    <ul class="info">
      <li>Distance:&nbsp;<span class="distance"></span>&nbsp;meter</li>
      &mdash; <li>Duration:&nbsp;<span class="duration"></span></li>
<!--      &mdash; <li>Pace:&nbsp;<span class="pace"></span>/meter</li> -->
 <!--     &mdash; <li>Avg&nbsp;HR:&nbsp;<span class="avghr"></span>&nbsp;bpm</li> -->
      &mdash; <li>Elevation:&nbsp;+<span class="elevation-gain"></span>&nbsp;meter,
        -<span class="elevation-loss"></span>&nbsp;meter
        (net:&nbsp;<span class="elevation-net"></span>&nbsp;meter)</li>
       &mdash;  Inspired by <a href="https://github.com/mpetazzoni/leaflet-gpx">leaflet-gpx</a>.<br>
    </ul>
  </footer>
</section>

<script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>
<script src="https://rawgithub.com/mpetazzoni/leaflet-gpx/master/gpx.js"></script>
<script type="text/javascript" src="../dist/leaflet.elevation-0.0.4.min.js"></script>
<script type="application/javascript">
  function display_gpx(elt) {
    if (!elt) return;

    var url = elt.getAttribute('data-gpx-source');
    var mapid = elt.getAttribute('data-map-target');
    if (!url || !mapid) return;

    function _t(t) { return elt.getElementsByTagName(t)[0]; }
    function _c(c) { return elt.getElementsByClassName(c)[0]; }

    var map = L.map(mapid);
    L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'iles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    }).addTo(map);


    new L.GPX("gpsfile.gpx", {
      async: true,
      marker_options: {
            startIconUrl: './lib/leaflet-gpx/pin-icon-start.png',
            endIconUrl: './lib/leaflet-gpx/pin-icon-end.png',
            shadowUrl: './lib/leaflet-gpx/pin-shadow.png'
      },
    }).on('loaded', function(e) {
      var gpx = e.target;
      map.fitBounds(gpx.getBounds());

      _t('h3').textContent = gpx.get_name();
      _c('start').textContent = gpx.get_start_time().toDateString() + ', '
        + gpx.get_start_time().toLocaleTimeString();
      _c('end').textContent = gpx.get_end_time().toDateString() + ', '
        + gpx.get_end_time().toLocaleTimeString();
      _c('distance').textContent = gpx.get_distance().toFixed(2);
      _c('duration').textContent = gpx.get_duration_string(gpx.get_moving_time());
<!--      _c('pace').textContent     = gpx.get_duration_string(gpx.get_moving_pace(), true); -->
<!--      _c('avghr').textContent    = gpx.get_average_hr(); -->
      _c('elevation-gain').textContent = (gpx.get_elevation_gain()).toFixed(0);
      _c('elevation-loss').textContent = (gpx.get_elevation_loss()).toFixed(0);
      _c('elevation-net').textContent  = (gpx.get_elevation_gain()
      - gpx.get_elevation_loss()).toFixed(0);
    }).addTo(map);
  }

  display_gpx(document.getElementById('demo'));

    var el = L.control.elevation();
    el.addTo(map);
    var g=new L.GPX("gpsfile.gpx", {
        async: true,
         marker_options: {
            startIconUrl: './lib/leaflet-gpx/pin-icon-start.png',
            endIconUrl: './lib/leaflet-gpx/pin-icon-end.png',
            shadowUrl: './lib/leaflet-gpx/pin-shadow.png'
          }
    });
    g.on('loaded', function(e) {
            map.fitBounds(e.target.getBounds());
    });
    g.on("addline",function(e){
        el.addData(e.line);
    });
    g.addTo(map);


</script>
</body>

How to change leaflet marker options dynamically?

$
0
0

I want to change the draggable state of leaflet marker on some event. Now, we use marker.options.draggable to get the draggable state of that marker. However, I want to set/change that draggable state in some event.

marker  = L.marker([lat,lng],{draggable:true});
draggable_state = marker.options.draggable;

But, below is not working:

marker.options.draggable=false;

How can achieve this?

Custom Styling OpenStreetMap without needing to host it yourself

$
0
0

I know it’s possible to edit the way in which OpenStreetMap display, with CSS-like (like MapCSS) stylesheets.
Is possible to do this without having to host your own tile server?

How to pass custom marker to polyline decorator

$
0
0

I am working with leaflet appliction, where user draw some shape.
A polyline added to that shape using leaflet.polyline.decorators.
I just want to know how to pass custom marker to L.Symbol.marker().

For example i am passing the custom marker but its not working.

Script

var myCustomMarker= L.icon({
                    iconUrl: 'assets/img/wallE.png',
                    iconSize: [30, 30], // size of the icon
                    iconAnchor: [5, 18], // point of the icon which will correspond to marker's location
                });
    new L.Marker(e.latlng, { icon: wallIcon, draggable: false }).addTo(curr);
        polylineWall.addLatLng([e.latlng.lat,e.latlng.lng]).addTo(curr);
        // Add coordinate to the polyline
        var decorator = L.polylineDecorator(polylineWall, {
        patterns: [
                { offset: 0, endOffset: 0, repeat: '10px', symbol: new L.Symbol.marker(myCustomMarker)}
                   ]
                   }).addTo(curr);

Console Error

Uncaught Error: iconUrl not set in Icon options (see the docs).

If someone have knowledge about this problem please help.Thanks for your time.

Using custom icon markers with Folium?

$
0
0

Given that Folium builds on the Leaflet JS library, I was wondering if it could provide the same functionality as Leaflet for custom icon markers.

Scanning through the tutorial here, I’m somewhat doubtful that this is possible, but I thought I would ask here to confirm. It looks as if the marker icons are limited to those provided on Bootstrap.

map_1 = folium.Map(location=[45.372, -121.6972], zoom_start=12,tiles='Stamen Terrain')
map_1.simple_marker([45.3300, -121.6823], popup='Some Other Location',marker_color='red',marker_icon='info-sign')
map_1.create_map(path='iconTest.html')

If this is not supported, is anyone familiar with another Python mapping framework that would support the use of markers with custom icons?

GeoJSON to GPX with togpx

$
0
0

I have a leaflet map that I use for directions (routing) and I’m trying to convert geoJSON to gpx (for exporting) using the togpx js.
Everything works okay and I can see the gpx in my console, but then it begins a 2nd iteration and replaces my lat/lngs with a null value.

Here’s my script:

$("#exportGPX").on('click', function (event) {
        GPXfile = '';
        raw = response.route.shape.shapePoints;
        var string = JSON.stringify(raw);
        var matches = string.replace(/([-d.]+),([-d.]+)/g, ' [$2,$1] ');
        var newMatch = JSON.parse(matches);
        var selectedGeojson = {"type": "FeatureCollection", "features": [
                {"type": "Feature",
                    "properties": {
                        "name": "Route",
                        "popupContent": "Your Route"},
                    "geometry": {"type": "LineString", "coordinates": newMatch}}]};
        GPXfile = togpx(selectedGeojson);
        console.log(JSON.stringify(selectedGeojson));
        data = 'data:application/octet-stream,' + encodeURIComponent(PGXis);
        location.href = data;
    });

Here’s the console log from the first iteration:

var gpx= "<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="togpx"><trk><name>Route</name><desc>name=RoutenpopupContent=Your Route</desc><trkseg><trkpt lat="38.625205" lon="-90.154541"/><trkpt lat="38.624858" lon="-90.154136"/><trkpt lat="38.624858" lon="-90.154136"/><trkpt lat="38.626113" lon="-90.152435"/><trkpt lat="38.626113" lon="-90.152435"/><trkpt lat="38.626834" lon="-90.153266"/><trkpt lat="38.626834" lon="-90.153266"/><trkpt lat="38.626113" lon="-90.152435"/><trkpt lat="38.624679" lon="-90.150726"/><trkpt lat="38.624679" lon="-90.150726"/><trkpt lat="38.625114" lon="-90.150138"/><trkpt lat="38.625606" lon="-90.149406"/><trkpt lat="38.626781" lon="-90.147766"/><trkpt lat="38.628807" lon="-90.144973"/><trkpt lat="38.628807" lon="-90.144973"/><trkpt lat="38.629535" lon="-90.145851"/><trkpt lat="38.629535" lon="-90.145851"/><trkpt lat="38.630081" lon="-90.145034"/><trkpt lat="38.630863" lon="-90.144004"/><trkpt lat="38.63084" lon="-90.143974"/><trkpt lat="38.630821" lon="-90.143867"/><trkpt lat="38.630828" lon="-90.143806"/><trkpt lat="38.630859" lon="-90.143753"/><trkpt lat="38.630962" lon="-90.143692"/><trkpt lat="38.631061" lon="-90.1436"/><trkpt lat="38.631175" lon="-90.143386"/><trkpt lat="38.631828" lon="-90.142089"/><trkpt lat="38.631858" lon="-90.14196"/><trkpt lat="38.631858" lon="-90.141815"/><trkpt lat="38.631904" lon="-90.141731"/><trkpt lat="38.632209" lon="-90.141502"/><trkpt lat="38.632362" lon="-90.141242"/><trkpt lat="38.633533" lon="-90.139656"/><trkpt lat="38.634185" lon="-90.138664"/></trkseg></trk></gpx>"

and here’s the 2nd:

var gpx= "<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="togpx"><trk><name>Route</name><desc>name=RoutenpopupContent=Your Route</desc><trkseg><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/><trkpt lat="undefined" lon="undefined"/></trkseg></trk></gpx>"

How can I fix this?

Making a Leaflet line feature more 'grabbable'

$
0
0

Is there a way to increase the buffer that makes a line clickable in Leaflet?

I know you can increase the width of the line, but the symbology of my feature should not be altered in this case; it should remain exactly as shown in the screenshots below.

For instance, here the line is clickable:

enter image description here

But here it is not, even though the cursor is only a few pixels off:

enter image description here

In OpenLayers I can achieve this pretty easily with the available styling options, which you can tweak to add an invisible buffer, but in Leaflet this does not seem to be possible.

Are there any simple ways to achieve this effect?

I am usinga GeoJSON, in case that makes a difference.


Leaflet zoom to polygon

$
0
0

I receive a polygon layer in Leaflet via ESRI REST. (similar to here )
I want to have a menu where I can zoom to specific polygons. (one button per polygon)

How can I do that?

Open new Tab with L.EasyButton

$
0
0

I added an L.EasyButton to my map. Now I want it – by clicking – to open a new tab with a specific address.

I tried this but it did not work:

L.easyButton, function(btn, map){
    onclick="window.open('http://www.website.com/page')" 
}).addTo(map);

Any ideas?

how to get map object in event?

$
0
0

I add a listener to a button

 L.DomEvent
    .addListener(selectList, 'click', L.DomEvent.stopPropagation)
    .addListener(selectList, 'click', L.DomEvent.preventDefault)
    .addListener(selectList, 'click', this._onMarkerChange);

And then I want to move map by panto function.

_onMarkerChange: function (){
    this._handlingClick = true;
    for (var opt in this) {
        if(this[opt].selected)
        {
            var lat = this[opt].getAttribute( "data-lat" );
            var lon = this[opt].getAttribute( "data-lon" );
            this.L.Map.panTo( new L.LatLng( lat, lon ) );
            break;
        }
    }
     this._handlingClick = false;
},

It has an error –Uncaught ReferenceError: map is not defined
How should I do? pass map object into this event?

KML NetworkLink/Region and Leaflet or OpenLayers

$
0
0

I have a kml with region and networklink that works fine with google earth and Google Maps API (apparently via a call to KMLOverlayService). The structure is somehow a quadtree structure.

The top first kml contains multiple regions linking to other kml that links to other kml until you get to the last kml containing actual vector data for your map view context.

Extract from first KML :

<NetworkLink>
<Region>
<LatLonAltBox>
<north>51.0874481</north>
<south>12.677843</south>
<east>-0.0617014</east>
<west>-63.0849152</west>
</LatLonAltBox>
<Lod>
<minLodPixels>42788</minLodPixels>
<maxLodPixels>-1</maxLodPixels>
</Lod>
</Region>
<Link>
<href>1/t.kml</href>
<viewRefreshMode>onRegion</viewRefreshMode>
</Link>
</NetworkLink>

So this works fine with Google products but i’m really looking for an open-source web API that supports this kind of KML tree/pyramid. Do you know if this is possible ?

Thanx in advance

Map with style (color, border) depending on property value

$
0
0

Using Leaflet combined with D3, I’m trying to apply a style (e.g. colorize or draw a border) to units that share a same property value.

Further explanations

Context: townships in France are grouped in local ‘federations’ (“communauté de communes” used as frameworks to carry local tasks: collecting garbage, managing schools…). It is usually admitted that these federations are formed according to a concept called “bassin de vie” (https://fr.wikipedia.org/wiki/Bassin_de_vie) which is the smallest territorial girth where people live. However, these federations may also be formed according to the global income of their townships’s inhabitants, and this is what I’m trying to visualise.

The data I’m using is shown below, and contains the ID of the federation every township is part of.

How can I draw the external borders of the townships being part of the same federation?

The data structure I use:

{"features": [{
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [x1, y1],
                [x2, y2], ...
                [x3, y3]]]
    },
    "properties": {
        "zip_code": "xxx",
        "township_name": "xxx",
        "township_income": xxx,
        "township_population": xxx,
        "federation_code": xxx
    }
},
Viewing all 198 articles
Browse latest View live