Below is my code to get current location on map
but before adding this i want to remove / reset map if control is already available on map.
this.map = L.mapbox.map('map', null, {}).
addControl(L.control.scale()).
setView(DEFAULT_LAT_LONG, DEFAULT_ZOOM);
L.control.locate({
locateOptions: {
maxZoom: 15
}
}).addTo(this.map);
You can use .removeFrom(map) the same way you use .addTo(map), but first you should assign your control to a variable:
var myCtrl = L.control.locate({
locateOptions: {
maxZoom: 15
}
}).addTo(this.map);
myCtrl.removeFrom(map); // remove it
myCtrl.addTo(map); // add it again
Related
Hello everyone I have some problems its about the current positionmarker in my leaflet its supposed to update every 3 second and it does but it everytime it puts a new "position" marker on the map and the old one stays how can i fix this?
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: '© Leaflet 2021',
tileSize: 512,
zoomOffset: -1,
id: 'mapbox/streets-v11',
accessToken: '######'
}).addTo(map);
var greenIcon = L.icon({
iconUrl: 'person.png',
iconSize: [35, 35], // size of the icon // the same for the shadow
popupAnchor: [0, -20] // point from which the popup should open relative to the iconAnchor
});
// placeholders for the L.marker and L.circle representing user's current position and accuracy
var current_position, current_accuracy;
function onLocationFound(e) {
var radius = e.accuracy / 2;
var marker;
L.marker(e.latlng, {icon: greenIcon}).addTo(map)
}
// wrap map.locate in a function
function locate() {
map.locate({setView: true, maxZoom: 15});
}
map.on('locationfound', onLocationFound);
// call locate every 3 seconds... forever
setInterval(locate, 3000);
An efficient way to fix this is to keep a reference to the marker you create, so that you can update its position rather than creating a new marker each time you get a location update. The reference needs to be held in a variable that is outside your callback function, but in scope when the callback is created.
For instance, your callback can check whether the marker already exists, and either create it and attach it to the map object for easy re-use, or just update its coordinates if it is already there:
function onLocationFound(e) {
var radius = e.accuracy / 2;
if (map._here_marker) {
// Update the marker if it already exists.
map._here_marker.setLatLng(e.latlng);
} else {
// Create a new marker and add it to the map
map._here_marker = L.marker(e.latlng, {icon: greenIcon}).addTo(map);
}
}
Having this reference will also let you edit the marker from other functions, e.g. to change the icon or popup, hide it from view, etc.
You can do it, for example, in the following way.
Add an ID (customId) to the marker:
const marker = L.marker([lng, lat], {
id: customId
});
And when you add a new marker remove the existing one with the code below:
map.eachLayer(function(layer) {
if (layer.options && layer.options.pane === "markerPane") {
if (layer.options.id !== customId) {
map.removeLayer(layer);
}
}
});
based on this tutorial (http://leafletjs.com/examples/layers-control.html), I've tried to add 2 layers for a WMS based solution. In the tutorial, they managed to add 2 layers (Street and GrayScales) and switch between them.
My code:
function getDefaultWmsValues() {
var layer1, layer2;
layer2= 'Street';
layer1= 'Satellite';
return {
url: "http://dummy.com/wms/service",
mapCenter: [1, 2],
startZoom: 15,
layer: [layer1,layer2],
imageFormat: 'image/jpeg',
autor: "WMS Dummy",
maxZoom: 17,
minZoom: 12,
version: '1.1.0',
interactiveMapBoundaries: [[123, 1234], [1245.164611, 17890.023279]],
usedProjection: L.CRS.EPSG4326
};
}
function getWmsConfig(wmsDefaultValues) {
return L.tileLayer.wms(wmsDefaultValues.url, {
layers: wmsDefaultValues.layer,
format: wmsDefaultValues.imageFormat,
version: wmsDefaultValues.version,
maxZoom: wmsDefaultValues.maxZoom,
minZoom: wmsDefaultValues.minZoom,
crs: wmsDefaultValues.usedProjection,
attribution: wmsDefaultValues.autor
});
}
function createLeafletMap(wmsDefaultValues) {
var map = L.map('map', {center: wmsDefaultValues.mapCenter, zoom: wmsDefaultValues.startZoom});
var wmsConfig = getWmsConfig(wmsDefaultValues);
wmsConfig.addTo(map);
L.control.scale().addTo(map);
map.setMaxBounds(wmsDefaultValues.interactiveMapBoundaries);
L.marker(wmsDefaultValues.mapCenter).addTo(map);
var baseMaps = {
"Layer Name 1": 'Satellite',
"Layer Name 2": 'Street'
};
L.control.layers(baseMaps).addTo(map);
return map;
}
var wmsDefaultValues = getDefaultWmsValues();
var leafletMap = createLeafletMap(wmsDefaultValues);
In the function getDefaultWmsValues(), I have 2 valid layers, layer1 and layer2. If I let either => layer: [layer1] or layer: [layer2], my code will alternatively show the desired layer.
However, when I try to configure both to be able to switch with
layer: [layer1,layer2], only one of the layer will be shown and the widget to switch between layers like in the tutorial (Grayscale / Street) seems to be broken=> it will only show one of the layers...
Any help would be very much appreciated!
PS: I've replaced variables with dummy data, but my code is really built like this snippet...
Few things to notice here,
you're adding both the layers to a single variable, so they can't be treated as a two layers and hence can't be viewed in control box as two layers.
Further, you specify that you want to switch between layers, i.e., you want to see only one layer at a time, so, by default this functionality could only be achieved if we set our layers as base layer as mentioned here
Hence, you first need to change the getDefaultWmsValues() function as below
function getDefaultWmsValues() {
var layer1, layer2;
layer2= 'Street';
layer1= 'Satellite';
return {
url: "http://dummy.com/wms/service",
mapCenter: [1, 2],
startZoom: 15,
layer1: [layer1],
layer2: [layer2],
imageFormat: 'image/jpeg',
autor: "WMS Dummy",
maxZoom: 17,
minZoom: 12,
version: '1.1.0',
interactiveMapBoundaries: [[123, 1234], [1245.164611, 17890.023279]],
usedProjection: L.CRS.EPSG4326
};
}
Similarly, you need to create modify getWmsConfig() function, and pass the layer attribute separately as shown below
function getWmsConfig(wmsDefaultValues, layer) {
return L.tileLayer.wms(wmsDefaultValues.url, {
layers: layer,
format: wmsDefaultValues.imageFormat,
version: wmsDefaultValues.version,
maxZoom: wmsDefaultValues.maxZoom,
minZoom: wmsDefaultValues.minZoom,
crs: wmsDefaultValues.usedProjection,
attribution: wmsDefaultValues.autor
});
}
Now, call the getWmsConfig() two times passing one layer each time
var wmsConfig1 = getWmsConfig(wmsDefaultValues,wmsDefaultValues.layer1);
var wmsConfig2 = getWmsConfig(wmsDefaultValues,wmsDefaultValues.layer2);
wmsConfig1.addTo(map);
wmsConfig2.addTo(map);
Now, add these two wmsConfig variables to control
var baseMaps = {
"Layer Name 1": wmsConfig1,
"Layer Name 2": wmsConfig2
};
Good Luck
I have a listener that will detect changes of the location of objects on databases. It will pass all the information of the object that is being changed.
I want to get all markers from the current map and find the marker that is affected. Once found, update the location.
But, I am still looking for the best ways to get all markers from the map and then I can update the location.
var map = L.map('map').setView([37.78541,-122.40787], 13);
var markers = new L.FeatureGroup();
var mapLink =
'OpenStreetMap';
L.tileLayer(
'https://{s}.tiles.mapbox.com/v4/examples.map-i87786ca/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZ2Vja29iIiwiYSI6IndzVjRGN0kifQ.lToORsjE0lkt-VQ2SXOb-Q', {
attribution: '© ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
var marker = createCircleMarker([44.977368, -93.232659]);
marker._id = "69"; // Id of the marker
map.addLayer(marker);
var socket = io();
socket.on('update location', function(obj) {
// Get all markers and find markers with attribute obj.name to
// update the location to [obj.lat,obj.lon]
});
Use eachLayer method on L.map. Like
map.eachLayer(function (layer) {
if (layer.options.name === 'XXXXX') {
layer.setLatLng([newLat,newLon])
}
});
Documentation at http://leafletjs.com/reference-1.2.0.html#map-eachlayer
To add an option without using map.eachLayer; all layers within the map are internally stored in map._layers.
Use
map._layers.forEach(function (layer) {
...
});
to iterate over ALL Layer elements. Not just the ones currently visible.
How to disable mobile touch event after the bing map is initialized?
We can disable before initializing by below code, using MapOptions object. However I'm looking after the Bing Map is initialized.
// Set the map and view options, setting the map style to Road and
// removing the user's ability to change the map style
var mapOptions = {credentials:"Bing Maps Key",
height: 400,
width: 400,
mapTypeId: Microsoft.Maps.MapTypeId.road,
disableTouchInput : true,
};
// Initialize the map
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
Any help is highly appreciated. Thanks in advance!!!
Most of the MapOptions do work when passed into the setOptions method of the map. For instance try this: map.setOptions({disableTouchInput: true});
Note that I've only tested this in IE. If you simply want to disable panning and zooming you can do this in a number of different ways. The first is to use map options, the other is to use the viewchange event, store the original map position and keep setting the map to the same view to lock it.
Since you can't set most of the MapOptions once the map is created you can only do this by swapping out your map for a new map with the options you want. This is a very basic example, but here is an example that shows and hides the bing logo which is one of the settings that you can't change with setOptions.
function switchMapOptions(active, inactive) {
try {
var newMap = new MM.Map($(inactive)[0], options);
for (var i = 0; i < map.entities.getLength(); i++) {
var loc = map.entities.get(i).getLocation();
newMap.entities.push(new MM.Pushpin(loc));
}
newMap.setView({center: map.getCenter(), zoom: map.getZoom(), animate: false});
map.dispose();
map = newMap;
}
catch (e) {
alert(e.message);
}
}
Full code at Jsfiddle: http://jsfiddle.net/bryantlikes/zhH5g/4/
I'm trying to update the lat/lng value of a marker after it is moved. The example provided uses a popup window to display the lat/lng.
I have a "dragend" event listener for the marker, but when I alert the value of e.latlng it returns undefined.
javascript:
function markerDrag(e){
alert("You dragged to: " + e.latlng);
}
function initialize() {
// Initialize the map
var map = L.map('map').setView([38.487, -75.641], 8);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
maxZoom: 18
}).addTo(map);
// Event Handlers
map.on('click', function(e){
var marker = new L.Marker(e.latlng, {draggable:true});
marker.bindPopup("<strong>"+e.latlng+"</strong>").addTo(map);
marker.on('dragend', markerDrag);
});
}
$(document).ready(initialize());
http://jsfiddle.net/rhewitt/Msrpq/4/
Use e.target.getLatLng() to get the latlng of the updated position.
// Script for adding marker on map click
function onMapClick(e) {
var marker = L.marker(e.latlng, {
draggable:true,
title:"Resource location",
alt:"Resource Location",
riseOnHover:true
}).addTo(map)
.bindPopup(e.latlng.toString()).openPopup();
// #12 : Update marker popup content on changing it's position
marker.on("dragend",function(e){
var chagedPos = e.target.getLatLng();
this.bindPopup(chagedPos.toString()).openPopup();
});
}
JSFiddle demo
latlng value is not in e.latlng but in e.target._latlng .
Use console.
While using e.target._latlng works (as proposed by this other answer), it's better practice to use
e.target.getLatLng();
That way we're not exposing any private variables, as is recommended by Leaflet:
Private properties and methods start with an underscore (_). This doesn’t make them private, just recommends developers not to use them directly.
I think the API changed.
Nowadays is: const { lat, lng } = e.target.getCenter();
if anyone is using react than you should use :
const map = useMap()
map.addEventListener("dragend" , ()=> {
const {lat , lng} = map.getCenter()
})