Change position of leaflet label - javascript

I'd like to add labels to my leaflet-markers, and then position them above and horizontally centered for the marker icon.
With the labelAnchor option in the Leaflet.label plugin I can manually adjust every label so that I get what I want, and for now I've added a fixed width to my labels so that I know the text will be centered. But there must be a better way to achieve this?
http://jsfiddle.net/NYGvibeke/frUf4/3/
<style type="text/css">
.labeltext { width: 120px; text-align: center; border:none; }
</style>
<script type="text/javascript">
var myIcon = L.icon({
iconUrl: 'http://icons.iconarchive.com/icons/visualpharm/icons8-metro- style/512/Maps-and-Geolocation-Marker-icon.png',
iconSize: [18, 30],
iconAnchor: [10, 30],
labelAnchor: [-80, -40]
});
var layer = new L.StamenTileLayer("toner-lite", {maxZoom: 10});
var map = new L.Map("map", {
center: new L.LatLng(30, 100),
zoom: 4,
maxZoom: 12,
minZoom: 2
});
map.addLayer(layer);
var marker1 = L.marker([25, 100], {icon: myIcon}).bindLabel('This is a label text', { noHide: true, className: 'labeltext'}).addTo(map);
</script>

Change
.labeltext { width: 120px}
to
.labeltext { width: auto}
The auto value will dynamically size the width of the label.
UPDATE
Actually, that's only part of it. Here's the rest in a jsfiddle. Basically, you need to dynamically assign the position based on the number of characters. It takes a little bit of calibration (depending on font typeface/size), but here's what I came up with for labelAnchor:
[-label[0].length*2.5-20, -40]

Related

how to set leaflet marker to center of div tag in leafletjs

I want the marker to be in the center of the map, but it is wrong.
I read the rest of the articles, but my problem was not solved.
var map = L.map('map').setView([lat, lng], 18);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk', {
maxZoom: 18,
id: 'mapbox.streets',
accessToken: 'pk',
attribution: 'nemajoo',
watch: true
}).addTo(map);
var LeafIcon = L.Icon.extend({
options: {
iconSize: [28, 60],
shadowSize: [50, 64],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76]
}
});
var greenIcon = new LeafIcon({iconUrl: 'images/mrk.png'});
var center = map.getCenter();
var marker = L.marker([center.lat, center.lng],{icon: greenIcon}).addTo(map);
The problem here could be in any of the 3 configurations given we don't have the image:
mrk.png has some spacing inside the image, this can be fixed with any image editing tool.
the options object, on the anchor tag moves the image, making it look like it's not centered.
When you set the center, as far as I can see, you first get the center from the map, then use this center to position the icon, this is nicely done but markers with distant zooming don't represent it's center accurately.
In resume:
The problem is on the png or the anchor configuration, modify those values and try again.
If this does not work you can upload a sample minimal project so we can check (don't upload api keys or similar)

Trigger click on leaflet marker

I have a bunch of leaflet markers on the map. Each marker is held in array markers. The markers are created dynamically (during an ajax call).
var markers = [];
.
.
var marker = L.marker([mar.lat, mar.lng], {
// ...build the marker...
}
marker._leaflet_id = mar.id; // give the marker an id corresponding to the id of its corresponding div
var myHoverIcon = L.icon({
iconUrl: mar.imgUrl,
iconSize: [40, 40],
popupAnchor: [0, 0]
});
marker.on('click', function(e) {
alert('Marker clicked!');
marker.setIcon(myHoverIcon);
});
.
.
markers.push(marker);
Each marker has an id corresponding to a particular div (stored in data-mess_id on the div). The plan is to change the marker's icon when its corresponding div in the feed is clicked on.
$('#feed').on('mouseover', '.message', function() {
var cssid = $(this).attr('data-mess_id').toString();
var baz = $.grep(markers, function(m) {
return (m._leaflet_id == cssid);
});
baz[0].trigger('click'); // doesn't work
alert(baz[0].getLatLng()); // does work
// this also does not work:
var myHoverIcon = L.icon({
iconUrl: baz[0].imgUrl,
iconSize: [40, 40],
popupAnchor: [0, 0]
});
baz[0].setIcon(myHoverIcon);
});
It's all working fine except for the final bit. I just can't trigger a click event on the marker. I definitely have the correct marker because baz[0].getLatLng() is working. But baz[0].trigger('click') doesn't work.
I tried creating a new icon dynamically (myHoverIcon) but it doesn't work.
How do I trigger a click event on the marker?
Is there another way to change the marker icon?
To emulate a mouse click, you can use the fire method (inherited from Evented.fire) on the marker :
marker.fire('click');
And a demo
var map = L.map('map').setView([0, 0], 12);
var icon = L.icon({
iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png'
});
var marker = L.marker([0, 0], {icon: icon})
.addTo(map);
var myHoverIcon = L.icon({
iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-red.png'
});
marker.on('click', function(e) {
marker.setIcon(myHoverIcon);
});
document.querySelector('button').addEventListener('click', function() {
marker.fire('click');
});
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
button {position: absolute; left:10 px; top: 70px;}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<div id='map'></div>
<button>Click me</button>

LeafletJS how to display HTML Elements/DIV/Input Box/Button on specific position using LongLat

I'd like to ask about if it is possible or how do I add a "HTML Element" on spefic location on the map using Long Lat?
My goal is to add a Label and Text Input or a Text and Button pair sort of thing of specific position on the map.
Like for example:
Displaying a html + css control that displays a name and hobby:
Like this
Given the longitude and latitude place it on the map.
Is there a way doing this? How to do this?
Then maybe add something like a alert when clicking it.
You have many options:
Using L.popup's
Using L.tooltip's
Using an L.marker with an L.divIcon
Example:
var popup = L.popup({
closeButton: false,
autoClose: false,
closeOnClick: false
})
.setLatLng([48.85, 2.30])
.setContent(makeHtml(0));
var tooltip = L.tooltip({
permanent: true,
direction: 'left'
})
.setLatLng([48.84, 2.34])
.setContent(makeHtml(1));
var divIcon = L.divIcon({
html: makeHtml(2),
className: 'divIcon',
iconSize: [200, 50],
iconAnchor: [0, 0]
});
var marker = L.marker([48.85, 2.35], {
icon: divIcon
});
var map = L.map('map').setView([48.85, 2.35], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
popup.openOn(map);
map.openTooltip(tooltip);
marker.addTo(map);
function makeHtml(id) {
return '<label for="input_' + id + '">Input:</label><input type="text" value="my value…" id="input_' + id + '" />'
}
#map {
height: 200px;
}
.divIcon {
background-color: orange;
border: 1px solid black;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet-src.js"></script>
<div id="map"></div>
I can think about one way. I've used the L.divIcon for the same purpose. Here is a part of my code :
var yourPoint = L.divIcon({
className: 'map-marker-yourClassHere',
iconSize: null,
iconAnchor: [17, 35],
html:'<div class="text-marker">'+ txt +'</div>'
});
L.marker(latlng, {icon: yourPoint}).addTo(map);
You can simply put everything you want into this html option.

Negative value in anchor property

Chaps, using MarkerClusterer (Google Maps JS API), I'm not able to set a negative value for the position of the text inside the clusterer.
I got a custom cluster icon that requires the text to be at the top-right corner of the clusterer canvas.
Currently, I'm with this: . But the number should be inside the white cirlce on the top-right.
Is it possible? If so, why am I not achieving this (the code follows)?
var clusterStyles = [{url: 'imgs/mapa/cluster.png',
height: 56,
width: 48,
textSize: 15,
anchor: [0, 32]}];
Have a look at this working example. It is working fine. I took your script code and just replaced the url of the image:
var clusterStyles = [{
url: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m1.png',
height: 56,
width: 48,
textSize: 15,
anchor: [-20, 30]
}];
var options_markerclusterer = {
gridSize: 20,
maxZoom: 18,
zoomOnClick: false,
styles: clusterStyles
};
https://jsfiddle.net/mk06wc0k/
Minus values for the anchor are working good. If it's not working for you you have to show more code.

How to use Leaflet cluster plugin

I downloaded the dist dir from leaflet at Girhub
made a site on IIS so that I can reference it but I can not even follow the examples on the demo page.
I'm using asp.net to build my site and have the following in my ASPX page:
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<link rel="stylesheet" href="localhost/leaflet.label.css" />
<link rel="stylesheet" href="localhost/MarkerClusters/dist/MarkerCluster.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="localhost/MarkerClusters/dist/leaflet.markercluster-src.js"></script>
<script type="text/javascript">
var map = L.map('map',
{
crs: L.CRS.EPSG4326,
maxBounds: new L.LatLngBounds([-312, -180], [180, 312])
}).setView([0, 0], 0);
var myIcon = L.icon({
iconUrl: 'http://localhost/CustomIcons/Blue.png',
iconSize: [20, 20],
shadowSize: [50, 64],
iconAnchor: [10, 10],
shadowAnchor: [4, 62],
popupAnchor: [0, 0] });
Then this is the part I can't get:
var myMarkerCluster = L.markerClusterGroup({maxClusterRadius: 120});
//try to add markers
var testmarker1 = L.marker(new L.LatLng(0, 0), { icon: myIcon, draggable: false });
var testmarker2 = L.marker(new L.LatLng(10, 10), { icon: myIcon, draggable: false });
myMarkerCluster.addLayer(testmarker1);
myMarkerCluster.addLayer(testmarker2);
map.addLayer(myMarkerCluster);
Now, the odd thing I noticed is that before I added code for the clusters, I was able to right click on the map and get a leaflet pop up with the lat,lon. I have not removed that functionality in code but now, with the cluster code addition, if I right click, then I get a regular browser context menu. I don't understand what's going on and would like to know what's missing from the marker clustering that I'm trying to accomplish. Please advise....
Don't think there is one by default, you need to add context menu to leaflet, try this
http://leafletjs.com/plugins.html
https://github.com/aratcliffe/Leaflet.contextmenu

Categories

Resources