I am using leaflet js with openstreetmap in my project.
I have multiple circlemarkers at same place in my map.
I want to store some Id in that circlemarkers so that I can Identify that which data should be refereed when circlemarker is clicked.
My circlemarker is
var myMarker = L.circleMarker(myPoint, { title: 'unselected', radius: 20 });
myMarker.addTo(map);
Here I am using title for other purpose that's why I cant use it.
Can any one tell me some way to do this.
It sounds like you would like to add new functionality (functions, properties, etc) to an existing class. It would make sense to use object-oriented principals for this. For this purpose, I'd recommend you extending the CircleMarker class to add those properties.
customCircleMarker = L.CircleMarker.extend({
options: {
someCustomProperty: 'Custom data!',
anotherCustomProperty: 'More data!'
}
});
Now when you create your circle marker, create an instance of your extended object instead.
var myMarker = new customCircleMarker(myPoint, {
title: 'unselected',
radius: 20,
someCustomProperty: 'Adding custom data to this marker!',
anotherCustomProperty: 'More custom data to this marker!'
});
myMarker.addTo(map);
Now you can get the properties like you would any other option from the marker. This is just a simple case of extending, and you can do more as needed, such as adding other properties or functions to the object.
JSFiddle example: JSFiddle
With the current version of leaflet (0.8-dev) you can just set your custom properties on the marker object itself, without having to create a custom marker class...
function map() {
return L.map('leaflet-canvas',
{
maxZoom: 10,
minZoom: 0,
crs: L.CRS.Simple
});
}
var map = map().setView([0, 0], 10).on('click', onMapClick);
function onMapClick(e) {
var marker = L.circleMarker(e.latlng, {draggable:true});
marker.myCustomID = Math.floor((Math.random() * 100) + 1);
marker.on('click', onMarkerClick);
map.addLayer(marker);
// 'click' the new marker to show the ID when marker created
marker.fireEvent('click');
}
function onMarkerClick(e) {
alert(e.target.myCustomID);
}
Here is a TypeScript friendly way:
DataMarker.ts
import * as L from 'leaflet';
export class DataMarker extends L.Marker {
data: any;
constructor(latLng: L.LatLngExpression, data: any, options?: L.MarkerOptions) {
super(latLng, options);
this.setData(data);
}
getData() {
return this.data;
}
setData(data: any) {
this.data = data;
}
}
SomeOtherFile.ts
import { DataMarker } from './DataMarker';
const marker = new DataMarker([ lat, lng ], anyData, markerOptions);
--
Note 1: I decided not to merge the marker options with the data property
Note 2: Adjust the type of data if you need something more specific
marker is basically javascript object rite.
Below snippet solve my case simply.
var marker = new L.marker([13.0102, 80.2157]).addTo(mymap).on('mouseover', onClick);
marker.key = "marker-1";
var marker2 =new L.marker([13.0101, 80.2157]).addTo(mymap).on('mouseover', onClick);
marker2.key = "marker-2";
function onClick(e) {
alert(this.key); // i can expect my keys here
}
just to complete the picture , to create a handler which will respond to a mouse click on a marker and provide access the new options
function onMarkerClick(e) {
console.log("You clicked the marker " + e.target.options.someCustomProperty);
console.log("You clicked the marker " + e.target.options.anotherCustomProperty);
}
marker.on('click', onMarkerClick);
Try this Uniquely identifying Leaflet Markers , its working for me.
//Handle marker click
var onMarkerClick = function(e){
alert("You clicked on marker with customId: " +this.options.myCustomId);
}
//Create marker with custom attribute
var marker = L.marker([36.83711,-2.464459], {myCustomId: "abc123"});
marker.on('click', onMarkerClick);
I would recommend to structure in your data for your markers in the standard GeoJSON format, which makes it compatible for direct saving as shapefile, etc.
var myMarker = L.circleMarker(myPoint, { title: 'unselected', radius: 20 });
myMarker.properties.id = your_Id;
myMarker.addTo(map);
To retrieve the stored information and do things with it or pass it on to other parts of your program, showing a sample onclick function:
myMarker.on('click',markerOnClick);
function markerOnClick(e) {
my_ID = e.layer.properties.id;
console.log(my_ID, e.latlng);
// do whatever you want with my_ID
}
It took me a while to find out the e.layer.properties way to access the clicked marker's properties, so hope this helps someone. Most other examples only focused on yielding the lat-long of the marker, e.latlng.
Note that you can use this same code even with a whole layer / group of markers. The function will work on each individual marker.
I have a easy solution. options property in each circleMarker is the good place to store custom value.
var myMarker = L.circleMarker(myPoint, { custom_id: 'gisman', radius: 20 });
myMarker.addTo(map);
You can easily retrive the value in options.
function markerOnClick(e) {
var id = e.options.custom_id;
}
Related
I'm getting started with Ionic 2 / Angular 2 and trying to implement Mapbox into my app.
To display custom markers (code example here) Mapbox expects a DOM element, which, as far as I understand it, is not really the Angular way. I want to add a click event on the marker but because Mapbox uses elements, I'm not entirely sure how to approach this cleanly "the Angular way".
Basically, this is the latest version (showing the map and the marker works, but predictably when I click the marker the event listener can't find this.onMarkerClicked):
export class HomePage {
//(...)
refreshMapPosition() {
/*Initializing Map*/
mapboxgl.accessToken = this.config.mapbox_public_token;
this.map = new mapboxgl.Map({ /*https://www.mapbox.com/mapbox-gl-js/api/#map*/
style: 'mapbox://styles/mapbox/light-v9',
center: [this.Coordinates.longitude, this.Coordinates.latitude],
zoom: 16,
pitch: 80,
minZoom: 7.5,
maxZoom: 17,
container: 'map',
interactive: false,
});
var elCreature = document.createElement('div');
elCreature.className = 'icon-creature alpaca';
elCreature.addEventListener('click', function() {
this.onMarkerClicked();
});
var markerCreature = new mapboxgl.Marker(elCreature, {offset: [-20, -20]})
.setLngLat([this.Coordinates.longitude, this.Coordinates.latitude])
.addTo(this.map);
}
onMarkerClicked() {
console.log("click");
}
}
I'd be much happier if it was possible to have elCreature coming from a component, where I could use <div class="icon-creature alpaca" (click)="onMarkerClicked"></div>. What's the best approach there?
// on your marker HTML
var _self = this;
var _data = this.value;
el.addEventListener('click', function() {
self.markerClicked(_data);
});
// angular method
markerClicked(value){
console.log(value);
}
So I found something that maybe could help you, I created a marker as the documentation mentioned and then I got the element of that market with the getElement() function, after that I added the event to the marker, I do not know if it works with various markers but you can try.
var marker = new mapboxgl.Marker()
.setLngLat([lng, lat])
.addTo(this.map);
marker.getElement().addEventListener("click", function(){
console.log("function");
});
After sleep a while I found that there another thing that you can use, so you can create a Popup first and then add that Popou to a Marker object with the setPopup() method and actually it like an onClick event, because, when you click the Marker the Popup appears. Here is an example.
var popup = new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML("<h1>Hello</h1>");
var marker = new mapboxgl.Marker()
.setLngLat(coordinates)
.setPopup(popup)
.addTo(this.map);
The variable "coordinates" is an array, such that coordinates = [lng,lat], and this.map is just a variable under my Angular class that call to the mapboxgl.Map object.
You have to know that I am using Ionic 4 in this case. If you need more information please tell me.
Regards.
so I'm making a website using leaflet with dozens of base maps. I want to incorporate information about each map that is only visible if the user wants it. To do this, I would like to make an overlay map with popups, but I want the popups to change depending on the base map selected by the user.
How would I go about doing this?
Thank You So Much
You need to either use a plugin that keeps track of the base maps for you (like active layers) or you need to do it yourself.
If you are using the Leaflet layers control, you can subscribe to the basemapchange event to do this easily.
You need two things: active base layer management (easy) and dynamic popups (not too hard)
To wit:
First, here is the event handler to track active base layer when it changes.
map.on("baselayerchange",
function(e) {
// e.name has the layer name
// e.layer has the layer reference
map.activeBaseLayer = e.layer;
console.log("base map changed to " + e.name);
});
Because using L.marker().bindPopup() creates the popup content right there and does not support callbacks, you must manually create the popups in response to click event by calling map.openPopup() with your dynamic html (dynamic because it uses a variable: the active basemap name)
marker.on("click", function(e) {
var html = "Current base layer: <br/><b>" + map.activeBaseLayer.options.name + "<b>";
map.openPopup(html,
e.latlng, {
offset: L.point(1, -24)
});
});
Here is a working example on JS fiddle: http://jsfiddle.net/4caaznsc/
Working code snippet also below (relies on Leaflet CDN):
// Create the map
var map = L.map('map').setView([39.5, -0.5], 5);
// Set up the OSM layer
var baseLayer1 = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
name: "Base layer 1"
});
var baseLayer2 = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
name: "Base layer 2"
});
// add some markers
function createMarker(lat, lng) {
var marker = L.marker([lat, lng]);
marker.on("click", function(e) {
var html = "Current base layer: <br/><b>" + map.activeBaseLayer.options.name + "<b>";
map.openPopup(html,
e.latlng, {
offset: L.point(1, -24)
});
});
return marker;
}
var markers = [createMarker(36.9, -2.45), createMarker(36.9, -2.659), createMarker(36.83711, -2.464459)];
// create group to hold markers, it will be added as an overlay
var overlay = L.featureGroup(markers);
// show overlay by default
overlay.addTo(map);
// show features
map.fitBounds(overlay.getBounds(), {
maxZoom: 11
});
// make up our own property for activeBaseLayer, we will keep track of this when it changes
map.activeBaseLayer = baseLayer1;
baseLayer1.addTo(map);
// create basemaps and overlays collections for the layers control
var baseMaps = {};
baseMaps[baseLayer1.options.name] = baseLayer1;
baseMaps[baseLayer2.options.name] = baseLayer2;
var overlays = {
"Overlay": overlay
};
// create layers control
var layersControl = L.control.layers(baseMaps, overlays).addTo(map);
// update active base layer when changed
map.on("baselayerchange",
function(e) {
// e.name has the name, but it may be handy to have layer reference
map.activeBaseLayer = e.layer;
map.closePopup(); // any open popups will no longer be correct; take easy way out and hide 'em
});
#map {
height: 400px;
}
<script src="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.js"></script>
<link href="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.css" rel="stylesheet"/>
<div id="map"></div>
I am using jQuery's getJSON method to load external line data I've created in QGIS.
What I'm trying to do is toggle my layers on and off - simple check boxes, no radio button for the basemap. I'd also like all the layers to be off when the map is initially loaded.
My code
var map=L.map('map').setView([41.9698, -87.6859], 12);
var basemap = L.tileLayer('http://a.tile.stamen.com/toner/{z}/{x}/{y}.png',
{
//attribution: would go here
maxZoom: 17,
minZoom: 9
}).addTo(map);
//display geoJson to the map as a vector
var x = function(source, map)
{
var layers = L.geoJson(source,
{
style: function(feature){
var fillColor, side=feature.properties.side;
if (side==='Both') fillColor = '#309e2d';
else if (side==='Neither') fillColor = '#d90f0f';
else if (side==='West Only') fillColor = '#e27f14';
else if (side==='East Only') fillColor = '#2b74eb';
else if (side==='North Only') fillColor = '#eae42b';
else if (side==='South Only') fillColor = '#552d04';
else fillColor = '#f0f5f3';
return { color: fillColor, weight: 3.5, opacity: null };
},
onEachFeature: function(feature, geojson){
var popupText="<h1 class='makebold'>Border: </h1>"+feature.properties.name+"<br/>"+"<h1 class='makebold'>Which Side?: </h1>"+feature.properties.side;
geojson.bindPopup(popupText);
}
}).addTo(map);
};
$.getJSON("data/Knox.geojson", function(source){ x(source, map); });
$.getJSON("data/abc.geojson", function(source){ x(source, map); });
$.getJSON("data/xyz.geojson", function(source){ x(source, map); });
I tried assigning a variable before the L.geoJson function (var layers), and then L.control.layers(null, layers).addTo(map); That doesn't seem to work.
How does one create a layer control for multiple external geojson's that are already associated with a few callback functions (L.geoJson, style, and onEachFeature)? Thanks in advance.
EDIT:
Since you clarified that you want just the entire collection to be switched on/off, it is even more simple (and almost like what you tried by assigning your L.geoJson to var layers), but you have to take care of asynchronous processes.
To avoid this issue, you could do something like:
var myLayerGroup = L.layerGroup(), // do not add to map initially.
overlays = {
"Merged GeoJSON collections": myLayerGroup
};
L.control.layers(null, overlays).addTo(map);
function x(source, map) {
// Merge the GeoJSON layer into the Layer Group.
myLayerGroup.addLayer(L.geoJson({}, {
style: function (feature) { /* … */ },
onEachFeature: function (feature, layer) { /* … */ }
}));
}
$.getJSON("data/Knox.geojson", function(source){
x(source, map);
});
Then myLayerGroup will be gradually populated with your GeoJSON features, when they are received from the jQuery getJSON requests and they are converted by L.geoJson.
If my understanding is correct, you would like the ability to switch on/off independently each feature from your GeoJSON data?
In that case, you would simply populate your layers object while building the L.geoJson layer group, e.g. inside the onEachFeature function:
var layers = {};
L.geoJson(source, {
style: function (feature) { /* … */ },
onEachFeature: function(feature, layer){
var popupText = "<h1 class='makebold'>Border: </h1>" +
feature.properties.name + "<br/>" +
"<h1 class='makebold'>Which Side?: </h1>" +
feature.properties.side;
layer.bindPopup(popupText);
// Populate `layers` with each layer built from a GeoJSON feature.
layers[feature.properties.name] = layer;
}
});
var myLayersControl = L.control.layers(null, layers).addTo(map);
If you have more GeoJSON data to load and to convert into Leaflet layers, simply do exactly the same (adding built layer into layers in onEachFeature function) and build the Layers Control only once at the end, or use myLayersControl.addOverlay(layer).
Note: make sure to structure your code to take into account your several asynchronous processes, if you load each GeoJSON data in a separate request. Refer to jQuery Deferred object. Or simply create your Layers Control first and use the addOverlay method.
If you want them to be initially hidden from the map, simply do not add the geoJson layer to the map…
I learned a lot more about layer control in Leaflet than I expected, which is great.
#ghybs offered really helpful suggestions.
My issue was about toggling external geoJson files on and off, particularly with the getJSON jQuery method. I was trying to assign a variable within my multiple callbacks, like:
var layers=L.geoJson(source,{
{style: /*....*/},
{onEachFeature: /*....*/}}
and then just going L.control.layers(null, layers).addTo(map);
That doesn't work (why? I still can't explain-I'm quite the beginner-programmer). The way I did get this to work was by creating my style and onEachFeature functions separately, like this:
function borders (feature){
var fillColor, side=feature.properties.side;
if (side==='Both') fillColor = '#309e2d';
else if (side==='Neither') fillColor = '#d90f0f';
else if (side==='West Only') fillColor = '#e27f14';
else if (side==='East Only') fillColor = '#2b74eb';
else if (side==='North Only') fillColor = '#eae42b';
else if (side==='South Only') fillColor = '#552d04';
else fillColor = '#f0f5f3';
return { color: fillColor, weight: 3.5, opacity: null };
};
and
function popUp (feature, geojson){
var popupText="<h1 class='makebold'>
Border: </h1>"+feature.properties.name+"<br/>"+"<h1 class='makebold'>
Which Side</h1>"+feature.properties.side;geojson.bindPopup(popupText);
};
and then assigning these directly as callbacks into the getJSON method. By doing it this way, I could create a variable before "drawing" my geoJson to the map with L.geoJson(). Then I could assign the variable dynamically(?) to the layer control:
$.getJSON("data/xyz.geojson", function(source){
var xyz = L.geoJson(source, {
style: borders,
onEachFeature: popUp});
togglelayer.addOverlay(xyz, 'This name shows up on the control')});
});
I stored the variable togglelayer like this:
var togglelayer = L.control.layers(null, null,{collapsed: false}).addTo(map);
This post was also helpful: How to add two geoJSON feature collections in to two layer groups
I can have a bunch of locations with different categories to show on the map. Eventually I'd like to apply a filter on them. Probably the scenario is very familiar as I found many of them on the web while I was trying to solve my issue. I put the markers on my map and I can find no way to hide them. Here is how I try it:
function addLocations($content, id, map){
var $mapdiv = $content.find('div.map_div');
catValues = [map.catPrimary, map.catWhite, map.catGreen, map.catYellow, map.catRed, map.catBrown, map.catPurple, map.catGray, map.catOrange];
db.locations.all(function(obj){
$.each(obj, function(index, location){
if(location.value.nodeID == id){
var latitude = location.value.latitude;
var longitude = location.value.longitude;
var description = location.value.description;
var category = location.value.category;
var position = new google.maps.LatLng(latitude, longitude);
if(category == "0"){
homeLocation = position;
$mapdiv.gmap('get','map').setOptions({'center':position});
}
var marker = new google.maps.Marker({
position: position,
icon: "assets/img/marker_" + category + ".png",
category: category,
shadow: iconShadow,
});
marker.setMap( $mapdiv.gmap('get','map') );
$mapdiv.gmap('addMarker', marker).click(function() {
$mapdiv.gmap('openInfoWindow', { 'content': description + "<br/> (" + catValues[category] + ")"}, this);
});
}
});
markers = $mapdiv.gmap('get', 'markers');
for(var i = 0; i<markers.length; i++){
if(markers[i].category != "0"){
//"not primary, hiding
markers[i].setVisibile(false);
}
}
});
All the markers are shown and the ones that are supposed to be hidden are not. I also tried adding the markers to an array before I add them to the map and work with them, but no success. When I include the markers[i].setVisible(false) around a try and catch it says "Object # has no method 'setVisible'. Surprisingly if I test markers[i].getVisible() I get the value true.
I appreciate your help in advance.
I believe the correct code is markers[i].setMap(null);
https://developers.google.com/maps/documentation/javascript/overlays#RemovingOverlays
From the article:
Removing Overlays
To remove an overlay from a map, call the overlay's setMap() method, passing null. Note that calling this method does not delete the overlay; it simply removes the overlay from the map. If instead you wish to delete the overlay, you should remove it from the map, and then set the overlay itself to null.
If you wish to manage a set of overlays, you should create an array to hold the overlays. Using this array, you can then call setMap() on each overlay in the array when you need to remove them. (Note that unlike in V2, no clearOverlays() method exists; you are responsible for keeping track of your overlays and removing them from the map when not needed.) You can delete the overlays by removing them from the map and then setting the array's length to 0, which removes all references to the overlays.
LoadPin is a function to add a marker to a map. It initializes the layer on the first call. map is an openlayers map object.
But using map.removeLayer("markers") or "Markers", does not remove the markers from the map. I saw a mention of a destroy operation to do this but cant find that.
AND, how do I remove the popups?
var markers = null
function LoadPin(LL, name, description) {
var size = new OpenLayers.Size(36, 47);
var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
var icon = new OpenLayers.Icon('http://www.waze.co.il/images/home.png', size, offset);
if (markers == null) {
markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
}
var marker = new OpenLayers.Marker(LL, icon)
markers.addMarker(marker);
var bounds = markers.getDataExtent();
map.zoomToExtent(bounds);
map.addPopup(new OpenLayers.Popup.FramedCloud("test", LL, null,
"<div style='font-family:Arial,sans-serif;font-size:0.8em;'>" + name + "<br>" + description + "</div>",
anchor = null, true, null));
}
You can remove individual markers from a marker layer with:
markers.removeMarker(marker);
Removing the entire layer, with markers should be achieved with:
markers.destroy();
You should be able to remove a popup with:
map.removePopup(popup);
where popup is the Popup object created earlier.
I know this post is old but to remove all markers from the marker layer list use:
markerLayer.clearMarkers();
Try the any of below code i hope it will help you.
this.markerSource.removeFeature(this.iconFeature);
or
this.markerSource.removeFeature(iconFeature);