Geo-location with leaflet in JS - javascript

The following JS script (CSS/HTML included for completeness) is intended to open the leaflet map tiles and mark the user location. While it opens the map, it doesn't mark the user location. Why not?
<!DOCTYPE html>
<html>
<head>
<title>Leaflet GeoLocation</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([43, -79], 18);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
maxZoom: 18
}).addTo(map);
var newMarker = new L.marker(e.latlng).addTo(map);
</script>
</body>
</html>

You are not trying to get the user location at any point in this code.
This line :
var newMarker = new L.marker(e.latlng).addTo(map);
e is not defined in the code you provide. So you need to give it a latitude/longitude value.

Related

Using MapBox for Geolocation in html

I would like to display the address on dynamics CRM using MapBox API, i
have used Google API and it works perfectly, but now i would like to display it using map box.
I have looked at the forward geo-location feature of Mapbox but it's not yet clear.
So my variable my address variable will be coming from a field.
e.g var address = "6 Antares Drive, Ottawa, Ontario K2E 8A2, Canada";
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Add a geocoder</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.1.1/mapbox-gl-geocoder.min.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.1.1/mapbox-gl-geocoder.css' type='text/css' />
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibGF3aXgxMCIsImEiOiJjamJlOGE1bmcyZ2V5MzNtcmlyaWRzcDZlIn0.ZRQ73zzVxwcADIPvsqB6mg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-79.4512, 43.6568],
zoom: 13
});
var address = "6 Antares Drive, Ottawa, Ontario K2E 8A2, Canada";
var geocoder = new MapboxGeocoder({ accessToken: mapboxgl.accessToken });
geocoder.query(address); // how do i search and display this address
map.addControl(geocoder);
//map.addControl(new MapboxGeocoder({
// accessToken: mapboxgl.accessToken
//}));
</script>
</body>
</html>
How can the address be displayed similar to that of google map on the Html Page.
mapbox-gl-geocoder is a geocoder control for Mapbox GL JS, it's intended to provide a the user interface, that is, an input search box for searching on top of the Mapbox Geocoding API.
If you already have your query and just want to display that location on the map you're better to use the Mapbox JavaScript SDK with geocodeForward, see https://github.com/mapbox/mapbox-sdk-js#installation.
The Console.Log was very helpful, I found out that the data.features.center returns the coordinates which was all what i needed . the full code is below
<html>
<head>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body style="word-wrap:break-word;">
<div id='map'></div>
<script src='https://unpkg.com/mapbox#1.0.0-beta9/dist/mapbox-sdk.min.js'></script>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibGF3aXgxMCIsImEiOiJjamJlOGE1bmcyZ2V5MzNtcmlyaWRzcDZlIn0.ZRQ73zzVxwcADIPvsqB6mg';
console.log(mapboxgl.accessToken);
var client = new MapboxClient(mapboxgl.accessToken);
console.log(client);
var address = 't5h 0k7'
var test = client.geocodeForward(address, function(err, data, res) {
// data is the geocoding result as parsed JSON
// res is the http response, including: status, headers and entity properties
console.log(res);
console.log(res.url);
console.log(data);
var coordinates = data.features[0].center;
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: coordinates,
zoom: 14
});
new mapboxgl.Marker()
.setLngLat(coordinates)
.addTo(map);
});
</script>
</body>
</html>

Leaflet - pop up content for multiple markers

I have a geojson file for various sites. The file has site name information and address details.
Although I am able to display all my makers I am not sure how to show the attribute data on the pop up for the markers.
How do I display different information for each marker? At the moment all my marks show "Hello World"
I have included my code below
<head>
<!-- title -->
<title>Sky Fibre Network</title>
<!-- Reference the Leaflet CSS and JavaScript Files -->
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<div id="map"></div>
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0;}
#map{ height: 100% }
</style>
<script src="data/sites.geojson"></script>
</head>
<!-- Webmap contents -->
<body>
<script>
<!-- long and lat for UK & Zoom level for whole of UK -->
var map = L.map('map',{ center:[54.038486, -1.948915], zoom: 5});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var sitesLayer = L.geoJson(sites).addTo(map);
sitesLayer.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
</script>
</body>
Here is my answer guys.
<script>
<!-- long and lat for UK & Zoom level for whole of UK -->
var map = L.map('map',{ center:[54.038486, -1.948915], zoom: 5});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
function siteslabels (feature, layer){
layer.bindPopup("<p class='info header'>"+
"<b>" + feature.properties.SITE + "</b>" +
"</br>" + feature.properties.Address1 +
"</br>" + feature.properties.Address2 +
"</p>");
};
L.geoJson(sites,{
onEachFeature: siteslabels
}).addTo(map);
</script>

Leaflet map not loading

I am very new to leaflet so I am only just trying to grasp the basics. When following the tutorial online provided by Leaflet, I am struggling to get the map to load. If I use the coordinates provided I have no issues, however if I change the coordinates, nothing loads.
Can anyone help? Here's what I have:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Web Map</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<style>
#map {
width: 960px;
height:500px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map',{
center: [43.64701, -79.39425],
zoom: 15
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
</script>
this loads no bother but if I change the coordinates at all it doesn't load.
To change the map center you should change it in the map property: center: [43.00, -79.00].
var map = L.map('map',{
center: [43.00, -79.00],
zoom: 15
});
You should remember that first coordinate, latitude, takes number in range (-90, 90), while second one, longitude should be set in range (-180, 180). But anyway if you excess that second coordinate application will just calculate it's value as if it was in given ranges.
Maybe you mixed something up and tried to change it here L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',..? This line stands for loading basemap tiles, not centering the map.
Try to
var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',
{
attribution: false
});
var map = L.map('map',
{
zoomControl: true,
layers: [tileLayer],
maxZoom: 18,
minZoom: 6
})
.setView([43.64701, -79.39425], 15);
setTimeout(function () { map.invalidateSize() }, 800);
I wasn't able to reproduce your problem. Changing the center still loads a map. (Click [Run Code Snippet] button, below)
var map = L.map('map', {
//center: [43.64701, -79.39425], //comment out one of the centers
center: [40, -80],
zoom: 15
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Web Map</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<style>
#map {
width: 960px;
height: 500px;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
I noticed that you didn't have an end body, end html tag, so I added those.
What coordinates were you trying to change?

Map is not rendering in LeafletJS - getting blank page & no errors

I am trying to implement a map view that shows either online or offline tiles using the LeafletJS library for Europe (Zoom level 6 & 7).
I've generated the offline map tiles using a program called Mobile Atlas Creator 2.0.0 beta 1 using these settings:
When the atlas is generated, it creates a zip file containing the folder MapQuest with several sub folders and tile images.
So, I have downloaded the leaflet JS library version 0.7.7 from http://leafletjs.com/ and extracted into the following dir structure along with the offline map tiles:
Here are the contents of my index.html
<!DOCTYPE html>
<html>
<head>
<title>Europe Zoom Level 6 & 7</title>
<link rel="stylesheet" type="text/css" href="leaflet.css">
<script type="text/javascript" src="leaflet.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 100%;"></div>
<script type="text/javascript">
(function () {
// Objects
var isOnline = true;
var map = L.map('map').setView([51.505, -0.09], 6);;
// Generate tile layer url
var tileLayerUrl = isOnline
? 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'
: 'MapQuest/{z}/{x}/{y}.jpg';
// Set tile layer & set to map
L.tileLayer(tileLayerUrl, {
minZoom : 6,
maxZoom : 7,
attribution: '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
})();
</script>
</body>
</html>
I tried running this in offline mode as well as online mode to no avail; I am just getting a blank page. There are no errors in console.
Any ideas what I might be doing wrong here?
Okay, I have figured it out. The issue was caused by not setting custom styles to control height.
Here's the fixed working version:
<!doctype html>
<html lang="en">
<head>
<title>Europe Zoom Level 6 & 7</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="leaflet.css">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0;}
#map { height: 100% }
</style>
<script type="text/javascript" src="leaflet.js"></script>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
(function () {
// Objects
var isOnline = false;
var map = L.map('map').setView([51.505, -0.09], 6);;
// Generate tile layer url
var tileLayerUrl = isOnline
? 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'
: 'MapQuest/{z}/{x}/{y}.jpg';
// Set tile layer & add to map
L.tileLayer(tileLayerUrl, {
minZoom : 6,
maxZoom : 7,
attribution: '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors'
})
.addTo(map);
})();
</script>
</body>
</html>

Open Maps draggable circle with adjustable radius

I used to use google maps for this but their library has given me CSP 'unsafe-eval' errors. I want to remain secure so I'm starting to look at Open Maps.
Here's a screencast of the functionality I want to port over to Open Maps - http://screencast.com/t/5f5LeAesRr. On map click I want a circle that is draggable with an adjustable radius. Using leaflet I was able to get a circle to show on the map but it isn't draggable and the radius can't be adjusted by dragging as shown in the GMaps screencast. Any help is appreciated.
Figured it out using Leaflet and this Circle Editor plugin
Here's a small example using dependencies from https://github.com/kartena/Leaflet.EditableHandlers
<!DOCTYPE html>
<html>
<head>
<title>maps</title>
<style type="text/css">
#map { width: 481px;height: 300px; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.js"></script>
<!-- Plugin dependecies -->
<link rel="stylesheet" href="../lib/leaflet-0.6.4/leaflet.css" />
<link rel="stylesheet" href="../css/marker-extend.css" />
<script src="../lib/leaflet-0.6.4/leaflet-src.js"></script>
<script src="../src/L.CircleEditor.js" ></script>
<!-- End plugin dependecies -->
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<br>
<input id="lat" placeholder="lat" type="number"/>
<input id="lng" placeholder="lng" type="number"/>
<input id="radius" placeholder="radius" type="number"/>
<script>
var map = L.map('map').setView([40, -98.50], 4);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'examples.map-i875mjb7'
}).addTo(map);
var updateValues = function(circle) {
console.log(circle._latlng.lat, circle._latlng.lng ,circle._mRadius);
$('#lat').val(circle._latlng.lat);
$('#lng').val(circle._latlng.lng);
$('#radius').val(circle._mRadius);
}
// Set only one circle
var circleSet = false;
var onMapClick = function(e) {
if (!circleSet) {
var circleLocation = new L.LatLng(e.latlng.lat, e.latlng.lng),
circleOptions = {
color: '#0159E5',
fillColor: '#A8C5E4',
fillOpacity: 0.7,
extendedIconClass : 'extend-icon'
};
var circle = new L.CircleEditor(circleLocation, 786500, circleOptions);
map.addLayer(circle);
circleSet = true;
updateValues(circle);
circle.on('edit', function(){
updateValues(this);
});
}
}
map.on('click', onMapClick);
</script>
<!-- From https://github.com/kartena/Leaflet.EditableHandlers -->
</body>
</html>

Categories

Resources