When I run my function in the desired way, opening the context menu and then clicking the button, I can see my desired result the first time. Every time after that, it runs it always one time more. So the second time, I get the success message twice, the third three times, and so on.
This is for a Leaflet Maps project, by the way.
Also, I need to have the functions on the main map.on function, to get the coordinates of the click.
map.on('contextmenu', function(e) {
document.getElementById('context-menu').style.display = 'block';
document.getElementById('context-menu').style.left = e.originalEvent.x + 'px';
document.getElementById('context-menu').style.top = e.originalEvent.y + 'px';
function copyCoordinates() {
var lat = e.latlng.lat;
var lng = e.latlng.lng;
var zoom = map.getZoom();
var params = 'lat=' + lat + '&lon=' + lng + '&zoom=' + zoom;
var newUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + params;
navigator.clipboard.writeText(newUrl);
toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
document.getElementById('context-menu').style.display = 'none';
}
document.getElementById('copyCoordinates').addEventListener('click', copyCoordinates);
function copyCoordinatesFormatted() {
var lat = Math.floor(e.latlng.lat);
var lng = Math.floor(e.latlng.lng);
var formatted = '"lat": ' + lat + ',\n "lng": ' + lng + ',';
navigator.clipboard.writeText(formatted);
toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
var flag = true;
document.getElementById('context-menu').style.display = 'none';
}
document.getElementById('copyMarker').addEventListener('click', copyCoordinatesFormatted);
});
I tried adding flags, but that didn't work.
I fixed it by using onclick rather then EventListeners.
document.getElementById('copyCoordinates').onclick = copyCoordinates;
Thanks for the help!
Related
I am using MapBox to render a map. I have made a onClick function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.
Now what I want is to have a button below the table and when click on it I want it to execute a particular function, I have defined it but when clicked on it says Function is not defined
Code
map.current.on('click', function(e) {
var coordinates = e.lngLat;
var lng = coordinates.lng;
var lat = coordinates.lat;
console.log(lat);
console.log(lng);
var d = fetch("https://api.mapbox.com/geocoding/v5/mapbox.places/" + lng + "," + lat + ".json?access_token={token_value}").then(response => response.json()).then(function(data) {
console.log(data)
var str = "<table border='1'><tr><td><center>Title</center></td><td><center>Content</center></td></tr>"
for (let i in data["features"]) {
str = str + "<tr><td style='padding:5px'>" + data["features"][i]["place_type"][0] + "</td><td style='padding:5px'>" + data["features"][i]["place_name"] + "</td></tr>"
}
str = str + "</table>"
// button
str = str + "<button onClick={myFunction}>Save</button>"
function myFunction() {
console.log('Saved pressed');
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(str)
.addTo(map.current)
});
console.log(d);
});
Fix code as below
// button
str += `<button onclick="myFunction()"}>Save</button>`;
I would guess the button (and the function name defined for it) are created with a different scope than where you have defined your function. One of these might work:
Define your function as const myFunction = () => console.log("saved pressed").
Try referencing your function as this.myFunction
I have a setTimout loop being called repeatedly but the loop seems to catch up with itself and causes sticking on my page ect. I added a alert to see what was happening and i had the timer set to call every 10seconds, but the alert was being displayed oppressively faster until it was continuous
can anybody see why this is by my code below.
Many thanks
$(function(){
var running = setTimeout(function (){
var varLISTID = document.getElementById('datacatch').getAttribute("data-variable-LISTID");
var varUSERACCOUNTNAME = document.getElementById('datacatch').getAttribute("data-variable-USERACCOUNTNAME");
var varITEMACCOUNTNAME = document.getElementById('datacatch').getAttribute("data-variable-ITEMACCOUNTNAME");
var varSELECTEDUSER= document.getElementById('datacatchuser').getAttribute("data-variable-SELECTEDUSER");
var mylink = "loadmessages.php?listID=" + varLISTID + "&useraccountname=" + varUSERACCOUNTNAME + "&itemaccountname=" + varITEMACCOUNTNAME + "&selecteduser=" + varSELECTEDUSER;
$('#infobox1').load(mylink);
var myotherlink = "contactselect.php?listID=" + varLISTID + "&useraccountname=" + varUSERACCOUNTNAME + "&itemaccountname=" + varITEMACCOUNTNAME + "&selecteduser=" + varSELECTEDUSER;
$('#containercontact').load(myotherlink);
},10000);//10s
$(document).keypress(function() {
clearInterval(running);
})
});
I am prompting the user to click to create a single point marker on my map. I need to limit this to only one marker (which must be draggable). I have tried using a count variable with a comparison however this condition is not working for me (the user can make many markers - as shown in this image).
Here is my code:
var count = 0;
if (count <= 0) {
map.on('click', function(e){
count += 1;
var marker = L.marker(e.latlng,{draggable: true}).addTo(map);
var lat = e.latlng.lat;
var lon = e.latlng.lng;
alert("Lat, Lon : " + lat + ", " + lon);
});
}
Thanks in advance.
You can simply unbind the click event after the first click via off:
var onClick = function(e) {
map.off('click', onClick);
var marker = L.marker(e.latlng,{draggable: true}).addTo(map);
var lat = e.latlng.lat;
var lon = e.latlng.lng;
alert("Lat, Lon : " + lat + ", " + lon);
};
map.on('click', onClick);
More info in the Leaflet docs.
I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!
Here is the function I'm using to query data
function weather(position) {
var apiKey = '';
var url = '';
var data;
// console.log(position);
$.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {
$('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
$('.js-current-item2').html(data.currently.summary);
gif(data.currently.icon)
city(position.coords.latitude + "," + position.coords.longitude)
});
}
And here is the function for pulling images from GIPHY
function gif(status) {
var apiKey = '';
var url = 'http://api.giphy.com/v1/gifs/search?q=';
var query = status;
$.getJSON(url + query + apiKey, function(data) {
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
});
}
In your function gif(status) while setting the image choose a random value from data array instead of fixed
change
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
to
var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');
I am trying to reload a page after a few seconds and append the URL with a variable containing new Lat Long coordinates. Consider the code snippet below that works with Leaflet:
var latlng = getQueryVariable("latlng");
if(latlng){
console.log(latlng); //working
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("?");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
function onMapClick(e) {//Coordinate pop up
popup.setLatLng(e.latlng)
.setContent("Coordinates clicked are: " + e.latlng.toString())
.openOn(map);
var centerPoint = map.getSize().divideBy(2),
targetPoint = centerPoint.subtract([1500, 0]),
targetLatLng = map.containerPointToLatLng(centerPoint), //retrieve new lat longs
loadLatlng = "?latlng="+targetLatLng.lat+","+targetLatLng.lng;
setTimeout(function(){
//And herein lies the problem - the URL is being concatenated ??
window.location.href = window.location.href + loadLatlng;
window.location.href.reload(1);
}, 5000);
}
Does anyone know how to clear and then append the URL?
Thanks.
Build the url using the parts
window.location.href = [location.protocol, '//', location.host, location.pathname, loadLatlng].join("");
Same thing as
window.location.href = location.protocol + '//' + location.host + location.pathname + loadLatlng;
You could also do it a dirty way with splitting the current url on the ?
window.location.href = window.location.href.split("?")[0] + loadLatlng;