Move marker on click - javascript

I am creating a Leaflet-map, where I would like to move the marker by 1) drag and 2) mouse click. The coordinates of 'dragend' or mouse click are written to 'latitude' and 'longitude'. The drag is all well and good, but I am struggling with onclick.
The overall aim is to make the map more suitable for smart phone users.
Code: https://jsfiddle.net/oskjerv/pjgucx75
Docs: https://leafletjs.com/download.html

If you want the lalng when you click on the marker use this:
marker.on('dragend click', function (e) {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
});
if you want the latlng of the marker when you click on the map:
map.on('click', function (e) {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
});
if you want the latlng of the map where you clicked:
map.on('click', function (e) {
document.getElementById('latitude').value = e.latlng.lat;
document.getElementById('longitude').value = e.latlng.lng;
});

Your code doesn't have got a mouse click event code like dragging code.
marker.on('dragend', function (e) {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
//Confirmit.page.getQuestion('R3QX_pin_lat').setValue(marker.getLatLng().lat);
//Confirmit.page.getQuestion('R3QX_pin_lng').setValue(marker.getLatLng().lng);
});
You can write mouse click code similar to drag code
map.on('click', function (e) {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
});

Related

How can I stop a map click event from firing when clicking on a layer?

I have a click event that fires when clicking on the map. However, I also have a separate event when clicking on a marker layer. Is it possible to stop the map click event from firing when I click on a marker?
The map click event:
map.on('click', function (e) {
if (isAddingLocations) {
console.log(e.lngLat);
$('#formtable').modal('show');
clickCoords = e.lngLat.toArray();
document.getElementById("latitudef").value = String(clickCoords[1])
document.getElementById("longitudef").value = String(clickCoords[0]);
}
});
The marker click event:
map.on("click", "quebec", function (e) {
map.getCanvas().style.cursor = 'pointer';
var location = e.features[0].properties.location;
var province = e.features[0].properties.province;
var link = e.features[0].properties.link;
var coordinates = e.features[0].geometry.coordinates.slice();
timeadded = e.features[0].properties.timeadded;
document.getElementById("location").innerHTML = location + ", " + province;
document.getElementById("link").innerHTML = '<a class="btn btn-info btn-lg" href="' + link + '"target="_blank" role="button">More Info</a>';
document.getElementById("latitudee").innerHTML = coordinates[1];
document.getElementById("longitudee").innerHTML = coordinates[0];
document.getElementById("locatione").innerHTML = location;
document.getElementById("provincee").innerHTML = province;
document.getElementById("linke").innerHTML = link;
if (isAddingLocations) {
$('#formedit').modal('show');
}
else {
sidedivsize_toggle(sdiv3, sdiv1, sdiv2);
}
});
I was thinking maybe there could be a "not 'quebec'" expression or something in the layer parameter. Or perhaps a if the second event fires prevent the first one. Not sure how one could do any of those things. And of course, any other solution is welcome.
Found a work around in MB github if anyone else comes across this. https://github.com/mapbox/mapbox-gl-js/issues/9875
Essentially though, we stop the click event from doing anything as it bubbles up the dom chain from the Map Layer, to the Map. Example :
map.on('click', 'points', function (e) {
console.log('clicked on layer', e);
e.clickOnLayer = true;
});
map.on('click', function (e) {
if (e.clickOnLayer) {
return;
}
console.log('map clicked', e);
});
There are probably various solutions to this issue. One solution is the clickOneLayer function of Map-GL-Utils which fires different callbacks depending on whether a layer was clicked or whether a click missed everything.

Leaflet show popup on hover with the location of the mouse

I am using leaflet to show my geometry locations on the map. Now I have the popups working fine but when you hover over them, the location of the popup is in the middle of the line/string for example and not on the location of the mouse. Is it possible to change it to the location of the mouse so the map doesn't just suddenly move to a different location?
The code that I am using to open the popups in leaflet is as follows:
function addPopup(feature, layer) {
var popupContent = feature.properties.name;
layer.bindPopup(popupContent);
layer.on('mouseover', function (e) {
this.openPopup();
});
layer.on('mouseout', function (e) {
this.closePopup();
});
}
After #Falke Design pointed out that you could give the latlng coordinates to the openPopup function I made a cleaner version of the code:
function addPopup(feature, layer) {
var popupContent = feature.properties.name;
layer.bindPopup(popupContent);
layer.on('mouseover', function (e) {
this.openPopup(e.latlng);
});
layer.on('mouseout', function (e) {
this.closePopup();
});
}
You can convert the mousepoint to latlng and set the popup there.
layer.on('mouseover', function (e) {
var p = L.point([e.originalEvent.clientX,e.originalEvent.clientY])
var latlng = mymap.containerPointToLatLng(p);
this.openPopup(latlng)
});
layer.on('mousemove', function(e){
var p = L.point([e.originalEvent.clientX,e.originalEvent.clientY])
var latlng = mymap.containerPointToLatLng(p);
this.openPopup(latlng)
})
layer.on('mouseout', function (e) {

Click on markers mapbox

I have it so that clicking on the map creates a marker at that point. I am trying to add an event to the markers that will return the lnglat when the marker is clicked. The issue is I can't click the marker, the map just keeps creating new markers.
map.on('click', function(e){
let marker = new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map);
marker.on('click', function(){
console.log('hello');
});
});
Markers are simple HTML elements, so you can add an event listener directly to them by calling addEventListener on their DOM node:
map.on('click', function(e){
var el = document.createElement('div');
el.className = 'marker';
el.style.height = '20px';
el.style.width = '20px';
el.style.backgroundColor = 'black';
el.addEventListener('click', function(e){
// Prevent the `map.on('click')` from being triggered
e.stopPropagation();
console.log('hello');
});
let marker = new mapboxgl.Marker(el).setLngLat(e.lngLat).addTo(map);
});
https://codepen.io/eddydg/pen/gZpbRj?editors=1010

HERE Maps (JS v3) - Add event listener to info bubble

I'm trying to add a pointerenter event to a information bubble but it's not firing. I got it to work with a marker but not with a info bubble.
I've tried to add the eventhandler to the info bubble using addEventHandler like this:
var infoBubble = new H.ui.InfoBubble({lat:48.8567, lng:2.3508}, {
content: "<div>hello</div>"
});
infoBubble.addEventListener('pointerenter', function (evt) {
alert('pointerenter');
});
I've also tried adding the mouseOver event to the info bubble content element and that does not fire either.
var infoBubble = new H.ui.InfoBubble({lat:48.8567, lng:2.3508}, {
content: "<div>hello</div>"
});
mapUI.addBubble(infoBubble);
var infoBubbleContent = infoBubble.getContentElement();
infoBubbleContent.addEventListener('mouseOver', function(evt){
alert('mouse over');
});
Here's the full code.
// Initialize the platform object:
var platform = new H.service.Platform({
'app_id': 'xxx',
'app_code': 'xxx'
});
// Obtain the default map types from the platform object
var maptypes = platform.createDefaultLayers();
// Instantiate (and display) a map object:
var map = new H.Map(
document.getElementById('mapContainer'),
maptypes.normal.map,
{
zoom: 4,
center: {lat:50, lng:5}
});
// Enable the event system on the map instance:
var mapEvents = new H.mapevents.MapEvents(map);
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(mapEvents);
// create default UI with layers provided by the platform
var mapUI = new H.ui.UI.createDefault(map, maptypes);
var infoBubble = new H.ui.InfoBubble({lat:48.8567, lng:2.3508}, {
content: "<div>hello</div>"
});
infoBubble.addEventListener('pointerenter', function (evt) {
alert('pointerenter');
});
mapUI.addBubble(infoBubble);
/*
var infoBubbleContent = infoBubble.getContentElement();
infoBubbleContent.addEventListener('mouseOver', function(evt){
alert('mouse over');
});
*/
var standardMarker = new H.map.Marker(new H.geo.Point(40.4, -3.6833));
standardMarker.addEventListener('pointerenter', function (evt) {
alert('pointerenter');
});
map.addObject(standardMarker);
While the InfoBubble is an event target, the only event it dispatches itself is 'statechange'. However, after adding the bubble you can get the bubble's HTML element and use plain old HTML events on it:
var bubble = new H.ui.InfoBubble({lat:48.8567, lng:2.3508}, {
content: "<div>hello</div>"
});
ui.addBubble(bubble);
bubble.getElement().addEventListener('mouseover', function(e) {
console.log('hello there');
});
Note: The HTML for the bubble is only built AFTER it is added to the UI. Before the getElement() method return null.

Google Maps API v3 : Click events not triggered in firefox for custom marker

have created a map that I'm trying to have function similar to 'My Maps'. I have two dropdownlists on the right side, based on the selection in those ddl's, you can add a custom marker / icon. You select a marker type, then click the '+' button in the top right corner of the map, and then click where you want the marker added. My issue is, this works fine in IE, Safari, and Chrome, but not in firefox. The click event doesn't seem to fire.
Here is the location of the map : https://ait.saultcollege.ca/Michael.Armstrong/Index.html
The button to add the marker in the top right has an onclick event pointing to my 'placeMarker()' function. Here is the code for placeMarker(), createMarker() ...
function placeMarker() {
select("placeMarker");
var infowindow = new google.maps.InfoWindow({});
var catID = document.getElementById('category');
var typeID = document.getElementById('ddlType');
var category = catID.options[catID.selectedIndex].value;
var markerType = typeID.options[typeID.selectedIndex].value;
if (!markerType) {
alert("You must select an icon type.");
}
else {
var moveListener = google.maps.event.addListener(customMap, 'mousemove', function(event) {
if (mapMarker) {
mapMarker.setPosition(event.latLng);
} else {
mapMarker = createMarker(event.latLng, "test", markerType, "test");
}
});
var clickListener = google.maps.event.addListener(customMap, 'click', function(event) {
if (mapMarker) {
select("hand_b");
google.maps.event.clearListeners(customMap, 'mousemove');
google.maps.event.removeListener(listener);
mapMarker = createMarker(event.latLng, "test2", markerType, "test");
var htmlInfo = "" +
"Category:" + category + "" +
"Item:" + markerType + "" +
"Notes:" +
"Location:" + mapMarker.getPosition().toString() + "" +
"" +
"";
//infowindow.setContent(htmlInfo);
//infowindow.open(customMap, mapMarker);
}
});
}
}
function createMarker(latlng, title, icon, html) {
var mapMarker = new google.maps.Marker({
position: latlng,
map: customMap,
title: title,
icon: 'Images/' + icon + '.png'
});
return mapMarker;
}
function select(buttonId) {
document.getElementById("hand_b").className = "unselected";
document.getElementById("placeMarker").className = "unselected";
document.getElementById(buttonId).className = "selected";
}
Any help or suggestions would be awesome. Could this perhaps be a bug in ff?
I did something very similar for an open-source disaster software package. In this case, lets assume I selected "Fire" in my dropdown menu and this triggers addFire(). The listener on the markers will delete the point on a click or allow you to drag it. The map can only have one listener at a time, but each marker can still have its own listener at the same time.
Here is the code that worked on Chrome, Firefox and IE8:
//This function sets up the map for adding a fire icon
function addFire() {
//Kill old listener
if(listening)
google.maps.event.removeListener(listenerhandle);
//Start new listener
listenerhandle = google.maps.event.addListener(disasterMap, 'click', addFirePoint);
listening = true;
}//end addFire
//This function adds new fire points to the map and controls dragging and clicking
function addFirePoint(event) {
//Create the marker
var fireMarker = new google.maps.Marker({
icon: "./mapimgs/fire.png", position: event.latLng, map: disasterMap, draggable: true });
newFireMarkers.push(fireMarker);
fireMarker.setTitle("Fire");
//Listen for clicks on the new marker
google.maps.event.addListener(fireMarker, 'click', function() {
fireMarker.setMap(null);
//remove the marker from the array
for(i=0;i<newFireMarkers.length;i++) {
if(fireMarker.getPosition() == newFireMarkers[i].getPosition()) {
newFireMarkers.splice(i,1);
break;
}
}
}
); //end click listener
}//end addFirePoint

Categories