Mapbox GL JS camera center directly move to user's location - mapbox

How to make camera center (starting position) directly move to user's location first, except press the "GeolocateControl" button in Mapbox GL JS?
Thanks!
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = '...'
var map = new mapboxgl.Map({
container: 'map', // container id
center: [23.7548053,62.5590779], // starting position
zoom: 2,
style: 'mapbox://styles/mapbox/streets-v9'
});
// Add geolocate control to the map.
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));
</script>

Once the control is added to the map you can call trigger, see the documentation at https://www.mapbox.com/mapbox-gl-js/api/#geolocatecontrol#trigger
const geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
map.addControl(geolocate);
geolocate.trigger();

Related

Initialize mapBox map with dropped marker and search query

I have mapbox setup with geocoding so that a user can type in the 'Search' box, and once a location is selected, a marker is dropped at that location. I would like a marker to already be dropped on the map and a search term to already be entered into the Search box at the time of page load (I have a setup where a user selects a location, and if they go back to edit the page I want them to be able to see the location they had previously selected). Is this possible?
My code for initializing is:
initMap(lat, lng) {
const mapboxgl = require('mapbox-gl/dist/mapbox-gl.js')
mapboxgl.accessToken =
'access_token'
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11?optimize=true',
center: [lat, lng],
zoom: 8,
attributionControl: false,
})
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
})
map.addControl(geocoder)
map.on('load', () => {
geocoder.on('result', (result) => {
const inputResult = result.result
const coordinates = inputResult.geometry.coordinates
const placeName = inputResult.place_name
const lng = coordinates[0]
const lat = coordinates[1]
this.location = placeName
this.latLng = [lat, lng]
})
})
},
You can specify a query which is already displayed in the search input box and for which a marker is automatically added to the map by using MapboxGeocoder#query in conjunction with Map#on and the 'load' event. For example, the following code displays text in the input field and a marker for "High Park" on map load:
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-79.4512, 43.6568],
zoom: 13
});
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
});
map.addControl(geocoder);
map.on('load', () => {
geocoder.query('High Park');
});

How to draw a polyline using the mouse and leaflet.js

I would like to draw a polyline on a map with leaflet. The basic gesture that I would like to apply is:
User clicks and holds on the mouse button -> that defines the first marker. If the user holds the mouse button, and moves the mouse, a corresponding "rubber band" is displayed.
User releases the mouse button -> a second marker is added to the map and the 2 markers are linked by a line.
Starting from the second marker, the user can continue building a second line using the the same procedure as above.
The final result should be the set of coordinates/markers, linked by a polyline.
As Julien V and IvanSanchez said, you can implement some of the draw-like plugins
In example below:
You can see usage of Leaflet.draw plugin. Hope it helps :)
// center of the map
var center = [46.165164, 15.750443];
// Create the map
var map = L.map('map').setView(center,15);
// Set up the OSM layer
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Data © OpenStreetMap',
maxZoom: 18
}).addTo(map);
// Initialise the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
var options = {
position: 'topleft',
draw: {
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
},
shapeOptions: {
color: '#97009c'
}
},
polyline: {
shapeOptions: {
color: '#f357a1',
weight: 10
}
},
// disable toolbar item by setting it to false
polyline: true,
circle: true, // Turns off this drawing tool
polygon: true,
marker: true,
rectangle: true,
},
edit: {
featureGroup: editableLayers, //REQUIRED!!
remove: true
}
};
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw(options);
map.addControl(drawControl);
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
map.on('draw:created', function(e) {
var type = e.layerType,
layer = e.layer;
if (type === 'polyline') {
layer.bindPopup('A polyline!');
} else if ( type === 'polygon') {
layer.bindPopup('A polygon!');
} else if (type === 'marker')
{layer.bindPopup('marker!');}
else if (type === 'circle')
{layer.bindPopup('A circle!');}
else if (type === 'rectangle')
{layer.bindPopup('A rectangle!');}
editableLayers.addLayer(layer);
});
html, body, #map { margin: 0; height: 100%; width: 100%; }
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css" rel="stylesheet" />
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>
<div id='map'></div>
</body>
</html>

mapbox gl js disable controls

Is there a way to hide/remove or disable controls such as the controls from mapbox-gl-draw?
I add the draw control as follows
draw = mapboxgl.Draw({
drawing: true,
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});
map.addControl(draw);
Once a polygon is drawn I want to disable or hide the control, hence is no longer possible to draw another polygon.
Thanks a lot!
Gregor
You can actually disable the draw buttons (individually or as a group) with a little DOM interaction. In short, you can find the native CSS class for the draw menu ('mapbox-gl-draw_polygon', 'mapbox-gl-draw_point', etc.), add the disabled property, and add a CSS class with 'disabled'/grayed out styling. Example here: https://jsfiddle.net/emLs72zj/9/
// HTML
<div id="map">
</div>
<button id="disable-draw">
Disable Draw Btns
</button>
<button id="enable-draw">
Enable Draw Btns
</button>
// CSS
body { margin:0; padding:0; overflow:hidden;}
#map { position:absolute; top:20px; bottom:0; width:100%; }
.disabled-button {
-webkit-filter: opacity(.3) drop-shadow(0 0 0 #FFF);
filter: opacity(.3) drop-shadow(0 0 0 #FFF);
cursor: default !important;
}
// JS
mapboxgl.accessToken = 'pk.eyJ1IjoieXVuamllIiwiYSI6ImNpZnd0ZjZkczNjNHd0Mm0xcGRoc21nY28ifQ.8lFXo9aC9PfoKQF9ywWW-g';
var sfmapbox = [-122.413692, 37.775712];
// Create a new dark theme map
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/outdoors-v9', //stylesheet location
center: sfmapbox, // starting position
zoom: 12, // starting zoom
minZoom: 11,
});
map.on('load', function(){
// create control
var draw = mapboxgl.Draw({
drawing: true,
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});
// add control to map
map.addControl(draw);
var disableBtn = document.getElementById('disable-draw');
var enableBtn = document.getElementById('enable-draw');
var drawPolygon = document.getElementsByClassName('mapbox-gl-draw_polygon');
disableBtn.onclick = (e) => {
drawPolygon[0].disabled = true;
drawPolygon[0].classList.add('disabled-button');
};
enableBtn.onclick = (e) => {
drawPolygon[0].disabled = false;
drawPolygon[0].classList.remove('disabled-button');
};
})
Currently in 2020 you should use
mapboxDraw = new MapboxDraw({....
map.addControl(mapboxDraw);
map.removeControl(mapboxDraw);
The remove method for controls is not bound to the map object, but you can remove it by calling remove() on the control object. https://jsfiddle.net/9o9mknqh/
// create control
var draw = mapboxgl.Draw({
drawing: true,
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});
// add control to map
map.addControl(draw);
// remove control from map
draw.remove()
You can always hide the control (if that's what you want) like this.
controls: {
polygon: false, // true -> show, false -> hide
trash: true
}
You must handle how the control is updated after this control. As in react, if you create your own component for the MapboxDraw, you can simply change the params and let it re-render itself.

multiple point direction draw in GL mapbox

I have draw direction to more then 2 park in gl mapbox.
I have try this code but not work perfectly.
mapboxgl.accessToken = 'pk.eyJ1IjoiYWNoYWxwcmFqYXBhdGkiLCJhIjoiY2lyNGkwZGsxMDFpenUybHd5bjRtMjVjeiJ9.2teTa5MmVqOW-MDpryv56w';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/achalprajapati/cis1byfch0008hgnitiwbym9c',
center: [-122.222461, 37.172263],
zoom: 8
});
var directions = new mapboxgl.Directions({
unit: 'metric', // Use the metric system to display distances.
profile: 'walking', // Set the initial profile to walking.
container: 'directions', // Specify an element thats not the map container.
// proximity: [-122.222453, 37.172271] // Give search results closer to these coordinates higher priority.
});
debugger;
//map.addControl(new mapboxgl.Directions());
//map.addControl(directions);
map.on('load', function () {
directions.setOrigin([-122.222461, 37.172263]);
directions.addWaypoint(0, [-122.222461, 37.172263]);
directions.addWaypoint(1, [-122.483318, 37.724502]);
directions.setDestination([-122.483318, 37.724502]);
});
directions.on('route', function (e) {
console.log(e.route); // Logs the current route shown in the interface.
});
there was a breaking change in a recent update of mapbox-gl-js that caused the mapbox-gl-directions plugin to error.
Here is a working jsfiddle of your code with the new versions (v2.2.0 of mapbox-gl-directions plugin and v0.22.1 of mapbox-gl-js)
mapboxgl.accessToken = 'pk.eyJ1IjoiYWNoYWxwcmFqYXBhdGkiLCJhIjoiY2lyNGkwZGsxMDFpenUybHd5bjRtMjVjeiJ9.2teTa5MmVqOW-MDpryv56w';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/achalprajapati/cis1byfch0008hgnitiwbym9c',
center: [-122.222461, 37.172263],
zoom: 8
});
var directions = new mapboxgl.Directions({
unit: 'metric', // Use the metric system to display distances.
profile: 'walking', // Set the initial profile to walking.
container: 'directions', // Specify an element thats not the map container.
});
map.addControl(directions)
map.on('load', function () {
directions.setOrigin([-122.222461, 37.172263]);
directions.addWaypoint(0, [-122.222461, 37.172263]);
directions.addWaypoint(1, [-122.483318, 37.724502]);
directions.setDestination([-122.483318, 37.724502]);
});
directions.on('route', function (e) {
console.log(e.route); // Logs the current route shown in the interface.
});

Reuse existing map instance for Leaflet directive

I'm trying to add the Leaflet Editable functionality to my current map which map is created by the leaflet directive. I'm getting the L.map instance with:
leafletData.getMap().then(function(map) {
// where map is the Leaflet map instance
}
However the Leaflet editable needs to set editable: true when the map is created.
So, is there a way to create a L.map instance
var map = L.map('map', {editable: true});
and then attach it to the Leaflet angular directive?
UPDATE:
I tried to add a hook to Leaflet
L.Map.addInitHook(function () {
this.whenReady(function () {
this.editTools = new L.Editable(this, this.options.editOptions);
console.log('L.map', this);
});
}
It creates the editTools successfully but the
map.editTools.startPolyline();
is still not working
Did you try adding editable: true to your defaults?
angular.extend($scope, {
defaults: {
editable: true
},
center: {
lat: 51.505,
lng: -0.09,
zoom: 8
}
});
<leaflet defaults="defaults" lf-center="center" height="480px" width="640px"></leaflet>
For anyone looking like me to make an existing map editable
var map = L.map('map', {editable: true});
is the same as
var map = L.map('map');
map.editTools = new L.Editable(map);