leaflet loads incomplete map - leaflet

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

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.

Leaflet map completely grey programmatically opening a popup tofa marker

I declare a leaflet map with
<div id="map" class="map-div"></div>
end initialize it with
var map = L.map('map').setView([51.178882, -1.826215],16);
$scope.map = map;
// OSM Mapnik
var osmUrl = "<a href='http://www.openstreetmap.org'>Open StreetMap</a>";
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + osmUrl,
maxZoom: 18,
}).addTo(map);
I grab some data from my server, and and markers to the map, in a loop, by calling this function (it's AngularJS, but I doubt that that plays a role):
$scope.AddMarkerToMap = function(companyData, index, array)
{
var companyName = companyData.company_name;
var latitude = companyData.latitude;
var longitude = companyData.longitude;
var cssClassname = 'comapny_has_no_present_workers';
if (companyData['currentWorkers'] > 0)
cssClassname = 'comapny_has_present_workers';
var pubLatLng = L.latLng(latitude,longitude);
// see https://leafletjs.com/reference-1.4.0.html#marker
var marker = L.marker(pubLatLng,
{
// this is the tooltip hover stuff
title: companyData['currentWorkers'] + ' current matches ' + companyData['previousWorkers'] + ' previous matches',
// see https://leafletjs.com/reference-1.4.0.html#icon
// this is a permanent label.
icon: new L.DivIcon({
className: cssClassname,
////html: '<img class="my-div-image" src="http://png-3.vector.me/files/images/4/0/402272/aiga_air_transportation_bg_thumb"/>'+
//// '<span class="my-div-span">RAF Banff Airfield</span>'
html: '<span>' + companyName + '</span>'
})
}).addTo($scope.map);
// see https://leafletjs.com/reference-1.4.0.html#popup
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
}; // AddMarkerToMap()
And the entire map is suddenly grey - with no problems reported in the developer console.
If I comment out the line
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
then everything displays as expected.
The code seems correct, as per the Leaflet documentation.
[Updtae] I just checked and if I only marker.bindPopup("<b>Hello world!</b><br>I am a popup."), the the map displays and I can click on the marker to display the popup. But when I try to programmatically open it with .openPopup(); the map is all grey.
[Update++] the map and its markers display just fine, with any one of
marker.bindPopup("<b>Hello world!</b><br>I am a popup.");
$scope.map.fitBounds(bounds, {padding: [50, 50]});
but with both, the map is grey :-(
What am I doing wrongly?
I think the issue comes from trying to change the map view (possibly through openPopup with autoPan, which is on by default) too often, typically in a loop without giving any delay for the map to actually set the view between each call.
IIRC, this is already identified as a limitation in Leaflet, but I could not find the exact thread in the issue tracker unfortunately.
Normally, a very simple fix is simply to remove the map view changes within your loop, and keep only the very last one.
In your case, if you have the default behaviour of only 1 Popup being opened at a time, then that would definitely be a valid solution: just open the popup of your last Marker.
If you did configure your map to keep several Popups open simultaneously, and you do want to open all of them through your loop, then make sure to disable autoPan (at least during your loop).

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.

Street labels in Mapbox Tile Layer too small

I have the following Leaflet map: JSFiddle link
<div id="mapid" style="height: 300px;"></div>
<script>
var mapboxTiles = L.tileLayer(mapBoxUrl, {
attribution: attributionText
});
var map = L.map('mapid')
.addLayer(mapboxTiles)
.setView([42.888284, -78.877222], 16);
</script>
The font size for the street labels is very small, to the point of being unreadable, and when you zoom in, the font size gets smaller. Is there a way to control the font size?
It looks like you have 512px sized tiles, but mapping the Earth as if they were 256px sized.
Therefore you need a combination of tileSize and zoomOffset options on your Tile Layer to compensate for these settings, and retrieve the correct view with readable sized text on the tiles:
var mapboxTiles = L.tileLayer(mapBoxUrl, {
attribution: '© Mapbox © OpenStreetMap',
tileSize: 512,
zoomOffset: -1
});
Updated JSFiddle: https://jsfiddle.net/zq02pnpg/2/
I had this problem too. On my case, the map was rendering just okay on desktop, but when it came to mobile devices, it)(The font size) gets really small and is not readable.
I tried doubling the tile size as well as the zoom offset and it worked.
var mapboxTiles = L.tileLayer(mapBoxUrl, {
attribution: '© Mapbox © OpenStreetMap',
tileSize: 1024,
zoomOffset: -2
});
I'm not sure if this is a violation of any kind but it worked for me!