add data to leaflet from from local file with javascript - javascript

I have seen many proposed solutions on the internet but none of them resolve my problem.
<script>
var url = "file:///home/myusername/Bureau/metroweb/Metropolis/templates/visualization/Circular City/edges.geojson"
// Initiate the map
var map = L.map('mapid').setView([48.832091014134825, 2.355001022600193], 10);
// This adds the tiles
L.tileLayer('http://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMapcontributors'
}).addTo(mymap);
var myLayer = L.geoJSON().addTo(map);
myLayer.addData(url);
</script>

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.

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.

Find my location with Leaflet [duplicate]

I'm trying to locate a user and set the map to this position with leaflet:
<script>
var map;
function initMap(){
map = new L.Map('map',{zoomControl : false});
var osmUrl = 'http://{s}.tile.openstreetmap.org/mapnik_tiles/{z}/{x}/{y}.png',
osmAttribution = 'Map data © 2012 OpenStreetMap contributors',
osm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
map.setView(new L.LatLng(51.930156,7.189230), 7).addLayer(osm);
}
function locateUser(){
map.locate({setView : true});
}
</script>
On execute the browser ask for permission, but then nothing happens? What's wrong with my code?
Here is a quick hack. I recommend this plugin https://github.com/domoritz/leaflet-locatecontrol
var loadMap = function (id) {
var HELSINKI = [60.1708, 24.9375];
var map = L.map(id);
var tile_url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var layer = L.tileLayer(tile_url, {
attribution: 'OSM'
});
map.addLayer(layer);
map.setView(HELSINKI, 19);
map.locate({setView: true, watch: true}) /* This will return map so you can do chaining */
.on('locationfound', function(e){
var marker = L.marker([e.latitude, e.longitude]).bindPopup('Your are here :)');
var circle = L.circle([e.latitude, e.longitude], e.accuracy/2, {
weight: 1,
color: 'blue',
fillColor: '#cacaca',
fillOpacity: 0.2
});
map.addLayer(marker);
map.addLayer(circle);
})
.on('locationerror', function(e){
console.log(e);
alert("Location access denied.");
});
};
loadMap('map');
You have an issue with the scope of your map variable. I have posted an example that fixes your code here: http://jsfiddle.net/XwbsU/3/
You should receive the browser geolocation popup when you click 'Find me!'.
Hopefully that helps you.
alternatively you can put all your code under getLocation() function and call that function at the loading of the webpage and you should be all set. I used this way and as soon as browser loads it popups a question to share data.

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.

How to start map with leaflet-js

I am trying to follow this quick start guide from the leaflet-js website. Here is my code:
function main(map_div_id, mapbox_access_token) {
var starting_coordinate = L.latLng(38.004697, 23.800735);
var starting_zoom = 8;
var map = L.map(map_div_id);
map.setView(starting_coordinate, starting_zoom);
L.tileLayer('https://api.tiles.mapbox.com/v4/mapbox.emerald/1/0/0.png?access_token=' +
mapbox_access_token,
{
accessToken: mapbox_access_token
}).addTo(map);
}
Here is what I see... Also zoom does not work.
You have broken url with zoom set to to 1, start point to 0,0. Change tileLayer to the following:
L.tileLayer('https://api.tiles.mapbox.com/v4/mapbox.emerald/{z}/{x}/{y}.png?access_token=' +
mapbox_access_token,
{
accessToken: mapbox_access_token
}).addTo(map);

Categories

Resources