Leaflet Map - change only img marker when click on it - javascript

Im triying to change image marker when user click on a specific one.
the problem here, is when i click on a market img changes, but when i click out side or onother market, nothing happens. (Screen shor below)
Please check here
This if my JS :
var LeafIcon = L.Icon.extend({
options: {
iconSize: [38, 95],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76],
},
});
var greenIcon = new LeafIcon({
iconUrl: project.path.base + "images/map/marker-in.png",
}),
redIcon = new LeafIcon({
iconUrl: project.path.base + "images/map/marker-active.png",
});
var testmarker = L.marker([data.lat, data.lng], { icon: greenIcon })
.on("click", (e, j) => {
e.target.setIcon(redIcon);
console.log("target", e.target)
})
.addTo(map)
.bindPopup($popin.innerHTML);

Remeber the last selection and reset that marker
var greenIcon = new LeafIcon({
iconUrl: project.path.base + "images/map/marker-in.png",
}),
redIcon = new LeafIcon({
iconUrl: project.path.base + "images/map/marker-active.png",
});
var lastMarker;
var testmarker = L.marker([data.lat, data.lng], { icon: greenIcon })
.on("click", (e, j) => {
if(lastMarker){
lastMarker.setIcon(greenIcon);
}
e.target.setIcon(redIcon);
console.log("target", e.target)
lastMarker = e.target;
})
.addTo(map)
.bindPopup($popin.innerHTML);
A different way is to set and reset the marker always when the popup is opend / closed:
var testmarker = L.marker([data.lat, data.lng], { icon: greenIcon })
.on("popupopen", (e) => {
e.target.setIcon(redIcon);
})
.on("popupclose", (e) => {
e.target.setIcon(greenIcon);
})
.addTo(map)
.bindPopup($popin.innerHTML);

Related

UserIcon cannot understand what's the right paths to start the simulation

how to pass getLatLng() on runSimulation correctly, I've tried many ways, but not getting what I want. It's working when I'm not dragging my marker, but when I drag them and run Simulation, it's giving me errors
function runSimulation() {
console.log("starting simulation");
initializeUserMarker(routes[0].marker);
const seconds = 60;
const numSteps = 20;
let pointsObj = {
i: 0,
};
setInterval(() => step(pointsObj), (seconds / numSteps) * 1000);
}
--
function initializeUserMarker(marker) {
const UserIcon = L.Icon.extend({
options: {
iconSize: [38, 95],
shadowSize: [0, 0],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76],
},
});
// user icon
var userIcon = new UserIcon({
iconUrl: "./assets/images/sport-car.png",
shadowUrl:
"http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
});
// add icon to map
userMarker = {
"id": atomicCounter,
"marker": L.marker(marker.getLatLng(), {icon: userIcon}).addTo(map)
};
}

how to change the colours based on role in leaflet open street maps

var locations = [{ name:"bus", latitude:"12.56", longitude:"25.15, role: "traveler" },
{ name:"bike", latitude:"13.56", longitude:"25.15, role: "traveler" },
{ name:"John", latitude:"14.56", longitude:"25.15, role: "Developer" },
{ name:"David", latitude:"12.56", longitude:"25.15, role: "Developer" },
{ name:"Mango", latitude:"13.56", longitude:"25.15, role: "Fruit" },
{ name:"Apple", latitude:"12.56", longitude:"25.15, role: "Fruit" }]
var map = L.map('mapid').setView([locations[0].latitude, locations[0].longitude], 8);
mapLink =
'ABC Corporation';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + mapLink,
maxZoom: 18,
}).addTo(map);
for (var i = 0; i < locations.length; i++) {
marker = new L.marker([locations[i].latitude,locations[i].longitude])
.bindPopup(locations[i].name)
.addTo(map);
}
This is my code I want to change the colour of the marker as per the role, right now if add two records with same latitude and longitude, I am able to see only latest one. how can I see the other marker also
For your first question "Change color":
You can't change the color of a marker but you can replace the default Icon, with another Icon.
https://leafletjs.com/examples/custom-icons/
var greenIcon = L.icon({
iconUrl: 'leaf-green.png',
shadowUrl: 'leaf-shadow.png',
iconSize: [38, 95], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
for (var i = 0; i < locations.length; i++) {
marker = new L.marker([locations[i].latitude,locations[i].longitude],{icon: greenIcon})
.bindPopup(locations[i].name)
.addTo(map);
}
To see both Markers on the same point, you can use a spiderfy Library, like: https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet or https://github.com/Leaflet/Leaflet.markercluster
From my code - function to return an icon with a colour selected by 'feature.properties.service':
function busservice(feature) {
var service = feature.properties.service;
var html = '<img class="arrow' + service +'" src="arrow-up-icon-29566.png">'
return new L.DivIcon({
iconSize: 40,
html: html});
}
and some CSS - a yellow icon for '26' -
img.arrow26 {
filter: invert(96%) sepia(50%) saturate(7493%) hue-rotate(1deg) brightness(102%) contrast(101%);
}

Problem with pointTolayer in my Leaflet Map

I tried to apply pointTolayer in my Leaflet Map it but it still throws the classic icons. There is an error in the Code.
$.getJSON("https://gist.githubusercontent.com/vassilaros/3791204ca226d5b236b4cd3106ef23cf/raw/PicnicSites.geojson",function(data){
var baseline_person = L.icon({
iconUrl: 'baseline_person.png',
iconSize: [18,18]
});
// add GeoJSON layer to the map once the file is loaded
L.geoJson(data, {
pointTolayer: function(feture, latlng){
return L.marker(latlng,{icon: baseline_person});
}
}).addTo(map);
});
Your L.geoJson should be L.geoJSON and pointTolayer should be pointToLayer respectively.
And then define iconSize and iconAnchor as L.icon params
const customMarker = new L.icon({
iconUrl: "marker.png",
iconSize: [32, 32],
iconAnchor: [10, 41],
});
axios
.get(
"https://gist.githubusercontent.com/vassilaros/3791204ca226d5b236b4cd3106ef23cf/raw/PicnicSites.geojson"
)
.then(response => {
L.geoJSON(response.data, {
pointToLayer: (feature, latlng) => {
return L.marker(latlng, { icon: customMarker });
}
}).addTo(map);
});
Demo

Adding IF statement to a featureLayer in Leaflet

I'm trying to filter what features get plotted to the map based on the users email that logs in to the site. So far, I've tried multiple options and keep getting stumped. Here's the code I have currently. Please help.
Here's the error: Uncaught TypeError: Cannot read property '_leaflet_id' of undefined at Object.stamp (leaflet.js:6) at e.addLayer (leaflet.js:6) at e._addLayers (leaflet.js:6) at e.initialize (leaflet.js:6) at new e (leaflet.js:6) at Object.o.map (leaflet.js:6) at app.js:810
var userEmail = $("#email").val();
if (userEmail.includes("fibertel")) {
var featureLayer = L.geoJson(null, {
filter: function(feature, layer) {
if (feature.properties.contractor === "FiberTel") return true;
},
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {
title: feature.properties["status_title_github"],
riseOnHover: true,
icon: L.icon({
iconUrl: "assets/pictures/markers/cb0d0c.png",
iconSize: [30, 40],
iconAnchor: [15, 32]
})
});
},
onEachFeature: function (feature, layer) {
if (feature.properties) {
layer.on({
click: function (e) {
identifyFeature(L.stamp(layer));
highlightLayer.clearLayers();
highlightLayer.addData(featureLayer.getLayer(L.stamp(layer)).toGeoJSON());
},
mouseover: function (e) {
if (config.hoverProperty) {
$(".info-control").html(feature.properties[config.hoverProperty]);
$(".info-control").show();
}
},
mouseout: function (e) {
$(".info-control").hide();
}
});
if (feature.properties["marker-color"]) {
layer.setIcon(
L.icon({
iconUrl: "assets/pictures/markers/" + feature.properties["marker-color"].replace("#",'').toLowerCase() + ".png",
iconSize: [30, 40],
iconAnchor: [15, 32]
})
);
}
}
}
});
} else if

Leaflet js adding custom marker pic fails

I am trying to add a custom marker picture but it keeps giving me the standard blue marker.
Here's my custom marker definition:
var aMarker = {
lat:location.lat,
lng:location.lng,
message: location.name,
// focus: true,
draggable: false,
getMessageScope: function() { return $scope; },
message: '<button class="icon-left ion-information-circled" ng-click=""></button> '+location.name,
compileMessage: true,
'icon': {
'type': "awesomeMarker", // i use awesomeMarker for font awesome
'icon': spotMarkerIcon, // a variable for my icon
}
};
var spotMarkerIcon = L.icon({
iconUrl: './images/SpotMarker.png'
});
angular.extend($scope,{
defaults: {
tileLayer: 'http://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',
maxZoom: 16,
zoomControlPosition: 'topright',
path: {
weight: 10,
color: '#800000',
opacity: 1
}
}
});
angular.extend($scope,{
markers : new Array()
});
$scope.markers.push(aMarker);
Have you tried to define the dimensions of the icon like this:
var greenIcon = L.icon({
iconUrl: 'leaf-green.png',
shadowUrl: 'leaf-shadow.png',
iconSize: [38, 95], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
EDIT: Here is a working example: http://jsfiddle.net/beLxbfep/

Categories

Resources