loading leaflet map in ajax loaded page renders no tiles? - leaflet

Hi I´m doing a phonegap app that loads my subpages with ajax and in one off them I´m trying to load a leaflet map.
It is not rendering the tiles?
I don´t know what I´m missing?
I load the leaflet css and js file in my index file and in my subpage that should display the map I have the following code:
<div id="themappage">
<div id="header" class="toolbar">
<h1>The Map</h1>
BACK
</div>
<div id="map"></div>
<script>
$(document).ready(function(){
var map = L.map('map');
L.tileLayer('http://{s}.tile.cloudmade.com/42dfb943872a465d89807eb88f6a1f4d/997#2x/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade'
}).addTo(map);
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng).addTo(map)
.bindPopup("You are within " + radius + " meters from this point").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
function onLocationError(e) {
alert(e.message);
}
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({setView: true, maxZoom: 16});
});
</script>
</div>
Any input appreciated, thanks.
Update!
Just found out if I use http://{s}.tile.osm.org/{z}/{x}/{y}.png instead off http://{s}.tile.cloudmade.com/42dfb943872a465d89807eb88f6a1f4d/997/256/{z}/{x}/{y}.png as the tile layer then it renders the tiles, why doesn´t the tiles from cloudemade render?

When I tried to load it, I got a 403 (Forbidden) error using that API-Key. Try to get another one (you did request your own right?). The reason that the OSM works is that it doesn't require an API-Key.
The API-Key is the part of the url that starts with 42dfb... and goes to the /. Replace that with a good key and you should be good to go.

Related

Is there a way to load a leaflet map instance without providing the map div container id?

From what I was able to find so far, it seems that the parent map div container must be available before I can instantiate a leafletjs map instance.
Is there a way to get the map instance content without providing the map container id?
My goal is to have something like this, so that I won't have to rely on an onload event to load the map in the page:
function getView() {
return `<div id="testLocations">
<div id="map">
${loadMap()}
</div>
</div>`;
}
function loadMap() {
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map);
var marker = L.marker([51.5, -0.09]).addTo(map);
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
return <map html content here>;
}
Any idea?
Thanks
Unfortunately no, it's impossible to initiate the map object before the map container initialized in the DOM.
If you add the map div element before creating the map object it will be ok.

Svelte with leaflet

I'm trying to find my way into Svelte combined with leaflet. Where I'm stuck is how to correctly split the leaflet components into files. For learning, I'm trying to build the official official leaflet quickstart with svelte.
This is how my app.svelte looks like:
<script>
import L from 'leaflet';
import { onMount } from "svelte";
import { Circle } from "./components/Circle.svelte";
let map;
onMount(async () => {
map = L.map("map");
L.tileLayer("https://a.tile.openstreetmap.org/{z}/{x}/{y}.png ", {
attribution:
'Map data © OpenStreetMap contributors, CC-BY-SA',
maxZoom: 18,
tileSize: 512,
zoomOffset: -1
}).addTo(map);
map.setView([51.505, -0.09], 13);
Circle.addTo(map);
});
</script>
<style>
html,body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
width: 100vw;
}
</style>
<svelte:head>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin="" />
</svelte:head>
<div id="map" />
and my circle component:
<script context="module">
import L from 'leaflet';
export let map_obj;
export let Circle = L.circle([51.508, -0.11], {
color: "red",
fillColor: '#f03',
fillOpacity: 0.5,
radius: 500
});
</script>
While this is working I do not think it's effective to consider every component and add it to the map with Circle.addTo(map);. How could I pass in the map object to the circle component or is there some better pattern to build the map with several components?
Note: I do know of svelte/leaflet but like to start from scratch for learning.
This seemingly easy task is complicated due to the not-really-straightforward lifecycle of frameworks like Svelte, and the really-straightforward let-me-do-DOM-stuff architecture of Leaflet.
There are several approaches to this. I'll describe one, based on nesting Svelte components for Leaflet layers inside a Svelte component for a Leaflet map, and using setContext and getContext to handle the Leaflet L.Map instance around. (I'm borrowing this technique from https://github.com/beyonk-adventures/svelte-mapbox )
So a Svelte component for a L.Marker would look like:
<script>
import L from 'leaflet';
import { getContext } from "svelte";
export let lat = 0;
export let lng = 0;
let map = getContext('leafletMapInstance');
L.marker([lat, lng]).addTo(map);
</script>
Easy enough - get the L.Map instance from the Svelte context via getContext, instantiate the L.Marker, add it. This means that there must be a Svelte component for the map setting the context, which will need the components for the markers slotted in, i.e.
<script>
import LeafletMap from './LeafletMap.svelte'
import LeafletMarker from './LeafletMarker.svelte'
</script>
<LeafletMap>
<LeafletMarker lat=40 lng=-3></LeafletMarker>
<LeafletMarker lat=60 lng=10></LeafletMarker>
</LeafletMap>
...and then the Svelte component for the Leaflet map will create the L.Map instance, set it as the context, and be done, right? Not so fast. This is where things get weird.
Because of how Svelte lifecycle works, children components will get "rendered" before parent components, but the parent component needs a DOM element to create the L.Map instance (i.e. the map container). So this could get delayed until the onRender Svelte lifecycle callback, but that would happen after the slotted children get instantiated and their onRender lifecycle callbacks are called. So waiting for Svelte to instantiate a DOM element to contain the map and then instantiate the L.Map and then pass that instance to the context and then getting the context in the marker elements can be quite a nightmare.
So instead, an approach to this is to create a detached DOM element, instantiate a L.Map there, i.e. ...
let map = L.map(L.DomUtil.create('div')
...set it in the context, i.e. ...
import { setContext } from "svelte";
setContext('leafletMapInstance', map);
...this will allow Leaflet layers instantiated by the slotted components to be added to a detached (and thus invisible) map. And once all the lifecycle stuff lets the Svelte component for the L.Map have an actual DOM element attached to the DOM, attach the map container to it, i.e. have this in the HTML section of the Svelte component...
<div class='map' bind:this={mapContainer}>
...and once it's actually attached to the DOM, attach the map container to it and set its size, i.e. ...
let mapContainer;
onMount(function() {
mapContainer.appendChild(map.getContainer());
map.getContainer().style.width = '100%';
map.getContainer().style.height = '100%';
map.invalidateSize();
});
So the entire Svelte component for this Leaflet L.Map would look more or less like...
<script>
import L from "leaflet";
import { setContext, onMount } from "svelte";
let mapContainer;
let map = L.map(L.DomUtil.create("div"), {
center: [0, 0],
zoom: 0,
});
setContext("leafletMapInstance", map);
console.log("map", map);
L.tileLayer("https://a.tile.openstreetmap.org/{z}/{x}/{y}.png ", {
attribution:
'Map data © OpenStreetMap contributors, CC-BY-SA',
}).addTo(map);
onMount(() => {
mapContainer.appendChild(map.getContainer());
map.getContainer().style.width = "100%";
map.getContainer().style.height = "100%";
map.invalidateSize();
});
</script>
<svelte:head>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""
/>
</svelte:head>
<style>
.map {
height: 100vh;
width: 100vw;
}
</style>
<div class="map" bind:this="{mapContainer}">
<slot></slot>
</div>
See a working example here.
As a side note, I'll say that one should think it twice before sandwiching Leaflet in another JS framework, and think twice about the architecture for this (slotted components seem the cleanest and most extensible, but maybe a big data structure and some imperative programming for the Leaflet bits would be simpler). Sometimes, making sense of the lifecycle implications of more than one framework working at once can be very confusing, and very time-consuming when bugs appear.

Leaflet map does not show up properly. Partially grey.

I have tried my best to take solutions here from diverse answers but my problem remains.
The map does not show up properly. A grey frame is taking almost 3/4 of the frame.
How the map shows up
<div id="map"></div>
<script>
var map = L.map('map',{scrollWheelZoom: false});
map.setView(<%= #location.latlng %>, 16);
marker = L.marker(<%= #location.latlng %>).addTo(map);
L.tileLayer('http://a.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Your attribution statement',
maxZoom: 20,
subdomains: '',
}).addTo(map)
$(document).ready(function(){
L.Util.requestAnimFrame(map.invalidateSize,map,!1,map._container);
});
</script>
See Data-toggle tab does not download Leaflet map.
You probably need a longer delay before calling map.invalidateSize(). Ideally listen to the event that opens your map container to its correct size.

how to create a jsfiddle using leaflet

I am struggling with jsfiddle trying to create a running example which uses leaflet.
because I was not successful I searched for some examples and found the following one working:
http://jsfiddle.net/kedar2a/LnzN2/2/
I then copied the example in a new fiddle
https://jsfiddle.net/aLn3ut5z/1/
but it is still not working...
when inserting the external resources, there was the following error:
jsfiddle.net says:
You're loading resources over HTTP not HTTPS, your fiddle will not
work. Do you wish to continue?
any suggestions what is wrong here?
p.s.: below is the code of the jsfiddle windows:
HTML:
<div id="map"></div>
CSS:
#map {
height: 500px;
width: 80%;
}
JAVASCRIPT:
// We’ll add a tile layer to add to our map, in this case it’s a OSM tile layer.
// Creating a tile layer usually involves setting the URL template for the tile images
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
osmAttrib = '© OpenStreetMap contributors',
osm = L.tileLayer(osmUrl, {
maxZoom: 18,
attribution: osmAttrib
});
// initialize the map on the "map" div with a given center and zoom
var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);
// Script for adding marker on map click
function onMapClick(e) {
var marker = L.marker(e.latlng, {
draggable: true,
title: "Resource location",
alt: "Resource Location",
riseOnHover: true
}).addTo(map)
.bindPopup(e.latlng.toString()).openPopup();
// Update marker on changing it's position
marker.on("dragend", function(ev) {
var chagedPos = ev.target.getLatLng();
this.bindPopup(chagedPos.toString()).openPopup();
});
}
map.on('click', onMapClick);
The Leaflet CDN doesn't support SSL yet. You can use something not requiring https, like playground-leaflet which is just a fork of JSBin with leaflet libraries easily selectable.
Alternatively, you could use Leaflet from cdnjs.net, which does support https.

leaflet loads incomplete map

I am dynamically adding a leaflet map to a div. The map is only shown partially, see picture. Once I resize the browser window the map is completely shown. Is there a way around this? I tried some initial ideas, see // in code. But none of them worked.incomplete map
function mapThis(lat,long,wikiTitle){
var div_Id= "#wikiExtract"+wikiTitle
var map_Id= "map"+wikiTitle
$(div_Id).append("<div id='"+map_Id+"' style='width: 600px; height:
400px'></div>");
var map = L.map(map_Id).setView([lat, long], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-
SA</a>'
}).addTo(map);
//$("#"+map_Id).css( "height", "500px" );
//map.invalidateSize()
//$("#"+map_Id).hide()
//$("#"+map_Id).show()
//$(window).trigger('resize');
}
you can use this code :
it work find for me.
setInterval(function () {
map.invalidateSize();
}, 100);
If at least you have the map working (except for the incompleteness of tiles loading), you could simply call map.invalidateSize() once your map's div container is revealed / inserted into DOM with final size.
Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default.
If using JQuery, the following code updates the size once the document is ready:
$(document).ready(function () {
mymap.invalidateSize();
});