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

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.

Related

Defining Leaflet map as dynamic map id (Cannot read property '_container' of undefined)

I have 2 different divs which using by leaflet as map object. I want to define my map objects into a function such as
html
<div id="mymap"></div>
<div id="mymap2"></div>
javascript
var map;
function define_map(map_id) {
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osm = L.tileLayer(osmUrl, {
maxZoom: 7
}),
map = new L.Map(map_id, {
center: new L.LatLng(51.505, -0.04),
zoom: 7
}),
drawnItems = L.featureGroup().addTo(map);
});
define_map("mymap");
define_map("mymap2");
$(".btnmarker").on("click", function() {
console.log(map);
L.DomUtil.addClass(map._container, 'my_crosshair-cursor-enabled'); // ON THIS LINE GETTING ERROR CODE Cannot read property '_container' of undefined
selected_tool = $(this).attr("id");
});
There is no problem, my maps seems working good until accessing features of them from button click event (this button will add a marker class to a map which i clicked on it)
But i'm getting map is not defined error. map is a variable and defined on top line of page.
Thanks inadvance

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();
});

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: 'Terms & Feedback'
});
How I change the content tileLayer by one create for me?
Thank you!
Like this:
// Provide your access token
L.mapbox.accessToken = 'pk.yyyyyyyyyyyyyyyy';
// Create a map in the div #map
L.mapbox.map('map', 'jonataswalker.kieo57jb'); //put yours here

loading leaflet map in ajax loaded page renders no tiles?

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.