How to specify accessToken for Mapbox with Leaflet - leaflet

From Mapbox site I tested this code and success:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.cs
<style>
body { margin:0; padding:0; }
.map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map' class='map'> </div>
<script>
var map = new L.Map('map', {
center: new L.LatLng(51.505, -0.09),
zoom: 8,
layers: new L.TileLayer('https://a.tiles.mapbox.com/v3/mapbox.world-bright/{z}
});
</script>
</body>
</html>
How can I access my own map with markers and features? I suppose the "mapbox.world-bright" would be replaced by my own map.id, but how can I set the accessToken?
For some reasons I need to stick with Leaflet, and don't want to switch to mapbox.js.

It's just a matter of using the right url in L.TileLayer. You'll need to add your mapId and token and use the correct attribution. It's also much better if you load the tiles from multiple subdomains because your browser can handle up to four connection as once. Code example:
L.tileLayer('https://{s}.tiles.mapbox.com/v4/{mapId}/{z}/{x}/{y}.png?access_token={token}', {
attribution: '© Mapbox © OpenStreetMap',
subdomains: ['a','b','c','d'],
mapId: 'myMapId',
token: 'myUserToken'
});
To add the features of your map you'll need to query those in a separate request. Here's an example using jQuery. You'll need to swap the MAPID and TOKEN for your mapid and token ofcourse:
$.getJSON('http://a.tiles.mapbox.com/v4/MAPID/features.json?access_token=TOKEN', function (data) {
// Assuming the variable map contains your mapinstance
var geojson = L.geoJson(data).addTo(map);
map.fitBounds(geojson.getBounds());
});
Here's a working example on Plunker: http://plnkr.co/edit/h8F3kC?p=preview

Related

How to Implement Open Route Service in Leaflet

Can I use Open Route Service api in leaflet map? I can't find working example to show how to integrate api key on the map. Now I'm using graphhopper and it's working flawless but now it have restrictions to use up to 5 points.
When I try to make waypoints via open route service I'm showing this error: Uncaught TypeError: L.Routing.openrouteservice is not a constructor
My code:
var mymap = L.map('mapid').setView([50.27264, 7.26469], 13);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors and ORS'
}).addTo(this.mymap);
var control = L.Routing.control({
waypoints: [
L.latLng(3.102739, 101.598077),
L.latLng(3.101861, 101.599037)
],
router: new L.Routing.openrouteservice('5b3ce3597851110001cf6248e3cd48b3c44c4e529f8fac67408d4257')
// routeWhileDragging: true
}).addTo(this.mymap);
I don't know does openrouteservice works with leaflet routing machine but I tried with MapBox and everything works fine. So now my map support walking directions.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Plain Leaflet API</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css' rel='stylesheet' />
<!-- Leaflet Map -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet-routing-machine/3.2.12/leaflet-routing-machine.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-routing-machine/3.2.12/leaflet-routing-machine.min.js"></script>
<!-- end Leaflet map -->
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
var mapboxTiles = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=' + L.mapbox.accessToken, {
attribution: '© Mapbox © OpenStreetMap',
tileSize: 512,
zoomOffset: -1
});
var map = L.map('map')
.addLayer(mapboxTiles)
.setView([42.3610, -71.0587], 15);
L.Routing.control({
router: L.Routing.mapbox(L.mapbox.accessToken,{
profile : 'mapbox/walking',
language: 'en',
}),
waypoints: [
L.latLng(40.779625, -73.969111),
L.latLng(40.767949, -73.971855)
],
}).addTo(map);
</script>
</body>
</html>
This is my HTML snippet for including the stuff I need for maps and routing:
<script src="scripts/maps/leaflet.js"></script> <!-- Include Leaflet JS -->
<script src="scripts/maps/leaflet-routing-machine.js"></script> <!-- Include the Leaflet Routing Machine -->
<script src="scripts/maps/polyline.min.js"></script> <!-- for Leaflet Routing Machine -->
<script src="scripts/maps/lodash.min.js"></script> <!-- for Leaflet Routing Machine -->
<script src="scripts/maps/corslite.js"></script> <!-- for Leaflet Routing Machine -->
<script src="scripts/maps/L.Routing.OpenRouteService.js"></script> <!-- Include the Open Route Service for Leaflet Routing Machine -->
<script src="scripts/maps/leaflet-providers.js"></script>
Then in typescript:
let router = (L as any).Routing.control({
router: new (L as any).Routing.openrouteservice(orsKey),
waypoints: [
L.latLng(startLatitude, startLongitude),
L.latLng(endLatitude, endLongitude)
],
routeWhileDragging: false,
show: false,
fitSelectedRoutes: false,
createMarker: function (i, waypoint, n) {
return null;
},
lineOptions: {
styles: [{ color: '#9f150b', opacity: 1, weight: 4 }]
}
});
router.addTo(map);
Only problem is the Open route service use POST requests in the latest API. So the L.Routing.OpenRouteService.js file needs updating

problem with leaflet in a smarty template

I'm using SmartyBC on version 3.1.33. In the smarty template the code of leaflet and openstreetmap will not run. The map will not open.
I've all tested with or without the script between {literal} {/literal}. The map will not open. However, in a normally html site the code works perfectly. What's the mistake?
<html>
<head><link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css">
<script src='https://unpkg.com/leaflet#1.5.1/dist/leaflet.js'></script>
#map {
height: 500px;
}
</head>
<body>
<div id="map"></div>
<script>
{literal}
var map = L.map('map').setView([43.64701, -79.39425], 15);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
L.marker([51.5, -0.09]).addTo(map)
.bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
.openPopup();
{/literal}
</script>
</body>
</html>
No error messages and no map. Thanks for help.
You didn't put #map styles in HTML <style>. I did that and the same code without {literal} tags worked.
https://codepen.io/anon/pen/vqVLjL

ArcGis layers on mapbox gl

I'm trying to add a layer from an api on ArcGis:
https://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_DATA/Facility_and_Structure/MapServer/1
In leaflet it is posible with:
L.esri.featureLayer({
url:"https://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_DATA/Facility_and_Structure/MapServer/1",
style: function () {
return { color: "#70ca49", weight: 2 };
}
}).addTo(map);
Is there a way to do this on mapboxgl?
Hi Jorge Monroy - Mapbox GL JS expects the data sources as such. In your case where you're wanting to load building footprints from an ArcGIS REST Service, your best bet is to load them as a geojson.
It looks like you're publishing the services from ArcServer 10.31. In that case, the way that I've loaded ArcGIS REST services is by exposing them through AGOL as explained there. If you have that option, that seems easiest. Otherwise, there are other (work-arounds)[https://gis.stackexchange.com/questions/13029/converting-arcgis-server-json-to-geojson] that I've no experience with.
Using Washington D.C. as an example, if you navigate to: http://opendata.dc.gov/datasets/building-footprints and then click on APIs, you can copy the link to the geojson service.
You can then load into MapboxGL JS through the data property of the geojson source shown there.
You can use leaflet-mapbox-gl.js to integrate leaflet and mapbox. Get token from mapbox and add it to below example to make it work.
References: https://github.com/mapbox/mapbox-gl-leaflet
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js'></script>
<script src="https://unpkg.com/mapbox-gl-leaflet/leaflet-mapbox-gl.js"></script>
<script src="https://unpkg.com/esri-leaflet/dist/esri-leaflet.js"></script>
<style>
html, body, #map {
margin:0; padding:0; width : 100%; height : 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var token = "";//add token before running this example
const INITIAL_VIEW_STATE = {
latitude: 45.528,
longitude: -122.680,
zoom: 13
};
var map = L.map('map').setView([45.528, -122.680], 13);
L.esri.basemapLayer("NationalGeographic").addTo(map);
var parks = L.esri.featureLayer({
url: "https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/Portland_Parks/FeatureServer/0",
style: function () {
return { color: "#70ca49", weight: 2 };
}
}).addTo(map);
var gl = L.mapboxGL({
accessToken: token,
style: 'mapbox://styles/mapbox/dark-v10'
}).addTo(map);
//To add anything on mapbox, first access the mapbox using getMapboxMap()
gl.getMapboxMap().on('load', () => {
//To load any layer on mapbox
//gl.getMapboxMap().addLayer();
});
var popupTemplate = "<h3>{NAME}</h3>{ACRES} Acres<br><small>Property ID: {PROPERTYID}<small>";
parks.bindPopup(function(e){
return L.Util.template(popupTemplate, e.feature.properties)
});
</script>
</body>
</html>

How do I delete multiple markers from a Leaflet map?

I am trying to delete all the markers on my map, but code below only the last added marker will be deleted.
Is there a way to get a new a instance of map i mean on click of a button is there a way to reinitialize the map in leaflet?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://npmcdn.com/leaflet#1.0.0-rc.3/dist/leaflet.css" />
</head>
<body>
<script src="https://npmcdn.com/leaflet#1.0.0-rc.3/dist/leaflet.js"></script>
<script src="../leaflet/lib/AnimatedMarker.js"></script>
<style>
#mapid { height: 500px; }
</style>
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([40.68510, -73.94136], 13);
L.tileLayer('http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {
attribution: '© Openstreetmap France | © OpenStreetMap'
}).addTo(mymap);
var marker = L.marker([40.68510, -73.94136]).addTo(mymap);
var marker = L.marker([40.68576, -73.94149]).addTo(mymap);
var marker = L.marker([40.68649, -73.94165]).addTo(mymap);
mymap.removeLayer(marker);
</script>
</body>
</html>
Instead of adding markers to the map, add your markers to a layerGroup and add the layerGroup to the map.
You can remove the markers using clearLayers() method.
var markers = L.layerGroup([marker1, marker2]).addTo(map);
markers.clearLayers();

A simple map using Mapbox API not working?

I am using Mapbox API to create simple maps and learn. I have written a very simple code to display the centre on some coordinates but the map won't show.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>A simple map</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = 'pk.eyJ1Ijoicm9oYW4wNzkzIiwiYSI6IjhFeGVzVzgifQ.MQBzoHJmjH19bXDW0b8nKQ';
var map = L.mapbox.map('map', {
center: [28.611690, 77.191008],
zoom: 13
});
</script>
</body>
</html>
What am I doing wrong here?
You're using the wrong parameters for L.mapbox.map, the first element is correct, that's for the ID of a HTML element or a reference to an HTML element. The second however, isn't for the options object. The second is for your mapbox mapid (or url, or tilejson), which you get when you create your own map via the Mapbox editor: https://www.mapbox.com/editor/#app The third parameter is for the options object.
L.mapbox.accessToken = 'pk.eyJ1IjoicGF1bC12ZXJob2V2ZW4iLCJhIjoiZ1BtMWhPSSJ9.wQGnLyl1DiuIQuS0U_PtiQ';
var map = L.mapbox.map('map', 'examples.map-i86nkdio', {
center: [28.611690, 77.191008],
zoom: 13
});