Leaflet map reload onclick - javascript

I have a gallery of image thumbnails and a image viewer. Each image has different #id has lat and long attached to it. I am triggering series of onclick events on clicking the thumbnail. The imagename, lat and long info is stored in a mysql table. The following are the functions I have written sofar.
function clickedImage(clicked_id) {
//series of functions
$.post("getLatLong.php",{"clickedimag":clickedImg},function(data){
var ll = JSON.parse(data);
var lat = parseFloat(ll[0]);
var long = parseFloat(ll[1]);
var pname = ll[2];
localStorage.setItem('lat',lat);
localStorage.setItem('long',long);
localStorage.setItem('cpname',pname);
//alert([lat,long]);
});
//Series of functions
}
All my other functions are working including I am able to save lat, long info into localStorage. The alert in the above function, clearly pops up with the lat and long attached to the image. To render the map, I am using the template given in the leaflet page.
$(function(){
var la = localStorage.getItem('lat');
var lon = localStorage.getItem('long');
var cpname = localStorage.getItem('cpname');
var mymap = L.map('mapid').setView([la,lon], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Ima$
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'my.access.token'
}).addTo(mymap);
var marker = L.marker([la, lon]).addTo(mymap);
marker.bindPopup("<b>" + cpname +"</b>").openPopup();
});
The above code works and renders the map correctly, however, only when I refresh the page. It is not changing the map asynchronously. I have tried this function too:
function getMyMap(la,lon) {
var la = localStorage.getItem('lat');
var lon = localStorage.getItem('long');
var mymap = L.map('mapid').setView([la,lon], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Ima$
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'myaccesstoken'
}).addTo(mymap);
}
and called this function inside my onClick event. I am getting the same result.
HTML
<div class="rhsbar" id="rhsbar" style="overflow:hidden;display:flex;flex-direction:column;">
<div id="mapid" >Loading map</div>
</div>
var h = $("#rhsbar").height();
var w = $("#rhsbar").width()+100;
document.getElementById("mapid").style.height=h+"px";
document.getElementById("mapid").style.width=w+"px";
How do I update the map with new coordinates without refreshing the page.

What you need is:
your_mapid.fitBounds(your_mapid.getBounds());
It will do a soft refresh of the map whenever something changes.

Related

BoatMarker with Leaflet, get a blank map when I try to add BoatMarker through python panel reactive.HTML

So I have been trying to place BoatMarker or WindBarbs to a leaflet map but when I put this code in, it returns a blank map. If I remove these variables the map will suddenly show up. I have no idea why this does not work, as there arent any errors or messages that pop up. I've put my code below, mostly taken from Awesome Panel example (https://awesome-panel.org/reactive_leaflet):
import panel as pn
class LeafletMap(pn.reactive.ReactiveHTML):
_template = """<div id="mapid" style="height:100%"></div>"""
__css__ = ["https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"]
__javascript__ = ["https://unpkg.com/leaflet#1.7.1/dist/leaflet.js", "https://unpkg.com/leaflet.boatmarker/leaflet.boatmarker.min.js"]
_scripts = {
"render": """
var mymap = L.map(mapid).setView([50, 0], 6);
state.map=mymap
var tileLayer = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'pk.eyJ1IjoibWFyY3Nrb3ZtYWRzZW4iLCJhIjoiY2s1anMzcG5rMDYzazNvcm10NTFybTE4cSJ9.TV1XBgaMfR-iTLvAXM_Iew'
}).addTo(mymap)
var marker1 = L.marker([48, -2], name='marker1');
var marker2 = L.marker([50, 0], name='marker2');
var marker3 = L.marker([52, 2], name='marker3');
var boatmarker = L.boatMarker([48, -2], name='marker4');
var layer1 = L.layerGroup([marker1, marker2, marker3, boatmarker]);
layer1.addTo(mymap)
""",
# Need to resize leaflet map to size of outer container
"after_layout": """
state.map.invalidateSize();console.log("invalidated");
""",
}
leaflet_map = LeafletMap(min_height=700, sizing_mode="stretch_both")
pn.Row(leaflet_map, sizing_mode="stretch_both").servable()
I've tried the same method for other leaflet custom markers and markings, like wind barbs (https://github.com/spatialsparks/Leaflet.windbarb/blob/master/README.md). The same issue also occurs.

Hover over show of Leaflet Marker from control panel

I have a map with different markers. The markers could be selected from the control panel. But, I would like to show the preview of the markers, when we hover over the marker tab in control panel.
If possilbe, the hover effect similar to the following jQuery example
Can anyone help me how this could be acheived? Following is the code:
// Map intialization
var map = L.map('map').setView([51.505, -0.09], 12.5);
// OSM layer
var OSM = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// OSM HOT
var OpenStreetMap_HOT = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors, Tiles style by Humanitarian OpenStreetMap Team hosted by OpenStreetMap France'
});
var singleMarker = L.marker([51.505, -0.09]);
// Layer controller
var baseMaps = {
"OpenStreetMap": OSM,
"OSM HOT": OpenStreetMap_HOT
};
var overlayMaps = {
"Marker": singleMarker
};
var layerControl = L.control.layers(baseMaps, overlayMaps, {
collapsed: false,}).addTo(map);
JSFiddle Example
Can you something like grabbing the event of the marker? Like so:
$('.leaflet-pane.leaflet-marker-pane').hover(function(){
alert('your code here?');
});
And from there call the tooltip event to show next to the marker?

Using openstreetmap with Bike Layer

I would like to use the bike layer like this one:
https://www.openstreetmap.org/#map=14/37.7874/-2.9519&layers=C
But I don´t know which url to use. At the moment I have just the default one:
var map = L.map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap'
}).addTo(map);
Any ideas?
Code from: https://github.com/mpetazzoni/leaflet-gpx

leaflet use satellite view, drupal 8?

I need instead of a basic view in leaflet (it's a map of the world), the satellite view, but I still need to be able to switch between them? How does this work, can anyone explain this to me?
Installed modules:
https://www.drupal.org/project/gmap
https://www.drupal.org/project/leaflet_more_maps
Without using any external plugin :
gpxpod.map = new L.Map('map', {
zoomControl: true
});
var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttribution = 'Map data © 2013 <a href="http://openstreetmap'+
'.org">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
var esriAerialUrl = 'https://server.arcgisonline.com/ArcGIS/rest/services'+
'/World_Imagery/MapServer/tile/{z}/{y}/{x}';
var esriAerialAttrib = 'Tiles © Esri — Source: Esri, i-cubed, '+
'USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the'+
' GIS User Community';
var esriAerial = new L.TileLayer(esriAerialUrl,
{maxZoom: 18, attribution: esriAerialAttrib});
var gUrl = 'http://mt0.google.com/vt/lyrs=s&x={x}&y={y}&z={z}';
var gAttribution = 'google';
var googlesat = new L.TileLayer(gUrl, {maxZoom: 18, attribution: gAttribution});
var baseLayers = {
'OpenStreetMap': osm,
'ESRI Aerial': esriAerial,
'Google map sat': googlesat
}
L.control.layers(baseLayers, {}).addTo(map);
This piece of code adds a standard control to switch between tile provider layers. It includes two satellite tile providers.
More info : http://leafletjs.com/reference-1.0.3.html#control-layers
I made a more detailed example of my question, but #JulienV came close to what I meant, But it wasn't entirely what I wanted, plus I already found his exact answer in another post. What I wanted was to know how to add more or less maps to the view:
var osmLink = 'OpenStreetMap',
thunLink = 'Thunderforest';
var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '© ' + osmLink + ' Contributors',
landUrl = 'https://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png',
thunAttrib = '© '+osmLink+' Contributors & '+thunLink;
var osmMap = L.tileLayer(osmUrl, {attribution: osmAttrib}),
landMap = L.tileLayer(landUrl, {attribution: thunAttrib});
var roadmap = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
var satellite = L.tileLayer('https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
var sat_text = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
And then I added each map to the array like this:
if($map_layouts['get_roads']) {
$roads = "\"Roads\": roadmap";
if($baselist == "") {
$baselist = $roads;
} else {
$baselist = $baselist . "," . $roads;
}
}
Then I needed to check if the $baselist wasn't empty:
if($baselist) {
$base_layout = "var baseLayers = {".$baselist."};";
} else {
$base_layout = "";
}
And then of course add the layers to the map:
L.control.layers(baseLayers).addTo(map);
I worked out the code with the google maps included. The osm and thun map was a nice example, but basically what this code does:
First I make if statements in php to see if the roads are included in the button I made. I pass the get_roads inside the array, so that the if statement returns true and then it sets $roads as the roadmap value, which is given in the map examples in the first code of this answer.
Then I check if $baselist isn't empty, because if it's empty it doesn't need a ,, but if it isn't empty, then it gets the $baselist, which would be the previous set value, then a comma and then the new value.
This was the markup of the layers and then I will pass the baseLayers as those values, which will create the maps inside the leaflet view, if the buttons are checked.

Leaflet panTo (or setview) function?

I want to create a panTo -function. When I click a link the map pans to the coordinates. But im not sure how to pass the value to the function. I'm starting with giving the link the Pointfield (pt) value like this:
Link
Then I've been trying this:
$("#dialog").on("click", ".marker", function(e) {
e.preventDefault();
map.panTo($(this).attr("value"));
});
That didn't work. I think it's a scope-issue where the function cant read the 'map' variable because it's not under the initial map script.
So my next idea is to create a "panTo"- function and place it under the inital map script (which would be the right scope) and call that function from the click event instead. Not sure it would work but Im wondering how to pass it the "value" from the link?
Thanks for your answers!
You can add navigation to your map by utilizing data attributes in your HTML. Save the latitude,longitude and zoom to something like data-position and then call those values with some JavaScript when the user clicks on the anchor tag. Here's some code to illustrate.
<div id="map">
<div id="map-navigation" class="map-navigation">
<a href="#" data-zoom="12" data-position="37.7733,-122.4367">
San Francisco
</a>
</div>
</div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade'
}).addTo(map);
document.getElementById('map-navigation').onclick = function(e) {
var pos = e.target.getAttribute('data-position');
var zoom = e.target.getAttribute('data-zoom');
if (pos && zoom) {
var loc = pos.split(',');
var z = parseInt(zoom);
map.setView(loc, z, {animation: true});
return false;
}
}
</script>

Categories

Resources