its possible to append actions to a function in javascript? - javascript

I had mi leaflet map on mapa.js like this:
var map = L.map('mapid').setView([-40, -59], 4);
and i want to add
var osm = L.tileLayer
('https://tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: 'ACCIONAR | OpenStreetMap',
minZoom: 3,
maxZoom: 21
}
).addTo(map);
When the user check a radio button, and erase it when unchecked.
I tried with php and i am frustrated.

Related

How to implement autocomplet place search box with Leaflet API

I would like to ask you how to implement just search box function from leaflet-search plugin and just for two countries. I want to make input field for location inserting with function of autocomplete.
I tried to implement search box with map first, but I can see just map and no search box.
Can you advice me where to start? I am new in it and I do not know way to go.
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 searchLayer = L.geoJson().addTo(map);
//... adding data in searchLayer ...
L.map('map', { searchControl: {layer: searchLayer} });
Check out the L.Control.Geocoder plugin for Leaflet. This plugin allows you to search for locations using a number of different services like Open Street Maps.
To limit the search results to a some countries, you have to configure the geocoding service that you use. I have created a quick example using OSM/Nominatim that limits the search results to the UK and US:
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);
let geoCoderOptions = {
collapsed: false,
geocoder: L.Control.Geocoder.nominatim({
geocodingQueryParams: {
// List the country codes here
countrycodes: 'gb,us'
}
})
}
L.Control.geocoder(geoCoderOptions).addTo(map);
See working example on codepen. If you search for a location (input in the top-right corner), you should only get results that are in the UK or the US. Hope this helps!

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.

Leaflet map reload onclick

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.

Leaflet with Customs Tiles seems to not be working

I am trying to use Leaflet in Combination with Custom Tiles to make a fictional Map, but it seems to not be working even when I set the Error Tile URL to a completely different image, it doesn't even show that.
My JS Code looks like this:
axios.get("https://crugg.de/udumap/map1/tiles/tiles.json").then((result) => {
let tilesData = JSON.parse(result.data.replace(/(\/\/)[A-Z a-z,:'()\/.#0-9]*/gm, ""));
console.log(tilesData.center);
let map = L.map('map', {
center: [tilesData.center[0], tilesData.center[1]],
zoom: tilesData.center[2]
}).setView([tilesData.center[0], tilesData.center[1]], tilesData.center[2]);
L.tileLayer('https://crugg.de/udumap/map1/tiles/{z}/{x}/{y}.png', {
attribution: 'Map data © UD:RP Map contributors',
minZoom: tilesData.minzoom,
maxZoom: tilesData.maxzoom,
zoomOffset: -1,
bounds: L.latLngBounds(L.latLng(tilesData.bounds[0], tilesData.bounds[1]), L.latLng(tilesData.bounds[2], tilesData.bounds[3])),
errorTileUrl: "https://crugg.de/udumap/map1/tiles/17/107729/82841.png"
}).addTo(map);
});
JSFiddle: https://jsfiddle.net/5xprc6n3/1/
This is my first time using Leaflet and I have no Idea why this isn't working.
You have to remove the bounds property.
L.tileLayer('https://crugg.de/udumap/map1/tiles/{z}/{x}/{y}.png', {
attribution: 'Map data © UD:RP Map contributors',
minZoom: tilesData.minzoom,
maxZoom: tilesData.maxzoom,
zoomOffset: -1,
errorTileUrl: "https://crugg.de/udumap/map1/tiles/17/107729/82841.png"
}).addTo(map);

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.

Categories

Resources