John Davidson

javascript - Google maps API use dragend to update one of multiple markers

0 comments
Message:


I'm using google maps API with multiple equipment locations fed from a Mysql database. I can successfully show the markers on the map and make them draggable. If I drag any marker to a new location, it prompts to ask if you want to update the database and if yes, supposedly sends the updated lat/lng to the database. This isn't working correctly, and instead always only updates the last item in the markers array.


Note that I have done this successfully with a single marker, and am able to update it anywhere I drag the new marker. But for multiple markers, I just don't seem to be able to get the current dragged marker's id and new lat/lon data to send back to the ajax call to update the database for that particular marker. I'm thinking it's because I'm not accessing the current marker's data, but I'm struggling with how to get that.


Any ideas what I'm doing wrong? I know it's got to be something simple I'm overlooking.


Here's a Fiddle to demonstrate my issue: JSFiddle


<!-- php stuff would be up here to get the database and feed the google API.    Instead here I've just created the const markers to show the markers. -->

<html>

<head>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</head>

<body>
<div id="mapCanvas"></div>
</body>

</html>
<style>#mapCanvas {
width: 100%;
height: 850px;
}

</style>

<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'hybrid'
};


// Display a map on the web page
map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
map.setTilt(100);

// Multiple markers location, latitude, and longitude
const mapIcon = "https://maps.google.com/mapfiles/marker_grey.png";
const markers = [
['Pike-1', 35.42526738862006, -81.172076628969, mapIcon, 10819],
['Pike-2', 35.425311504805924, -81.17216095766817, mapIcon, 10820],
['Pike-3', 35.425171475622824, -81.17188553479076, mapIcon, 10821],
['Pike-4', 35.42530668524588, -81.17134696588283, mapIcon, 10822],
['Pike-5', 35.42559347700399, -81.17218140606506, mapIcon, 10823],
['Pike-5', 35.426094498781885, -81.17195101338058, mapIcon, 26455],
['Pike-6', 35.42532308059036, -81.17215505637606, mapIcon, 26456]
];


// Place each marker on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
var eid = markers[i][4];
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
icon: markers[i][3],
equipid: markers[i][4],
title: markers[i][0]
});



//Add listener if marker is moved, then ask to update and call function if yes.
google.maps.event.addListener(marker, 'dragend', function() {
var mytitle = marker.equipid;
var latLng = marker.latLng;

let updateDB = confirm('Update location to database?');
if (updateDB) {
update_marker(latLng, mytitle);
console.log(latLng, mytitle);
}
});





// Center the map to fit all markers on the screen
map.fitBounds(bounds);

function update_marker(Marker, mytitle)
//This is the function that sends the update to the ajax call. Currently not working.
//with multiple markers, I can't get the selected marker equipment ID and new lat/lng.
{
//Update saved marker from DB and map using jQuery Ajax
var mLatLang = marker.getPosition().toUrlValue(); //get marker position - this does not get the marker position, but the last row of the result set from mysql
var mytitle = marker.equipid; //get marker equipment id - this currently gets the last row[id] of the mysql result set.
var myData = {
update: 'true',
name: mytitle,
latlang: mLatLang
};
$.ajax({
type: "POST",
url: "equipment-ajaxupdate-gps.php",
data: myData,
success: function(data) {
alert(data);
console.log(mytitle, mLatLang);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error! Update Failed!")
console.log(mytitle, mLatLang);
}
});
}


} //end of for( i = 0)

// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(19);
google.maps.event.removeListener(boundsListener);
});


} //End of function(initmap)



// Load initialize function
google.maps.event.addDomListener(window, 'load', initMap);


</script>


My Answer:
In order to update the correct marker's data in the database when it is dragged, you need to keep track of the marker's ID along with its position. One way to do this is to store the marker ID as a property of the marker object when you create it.

Here's an example of how you can modify your code to achieve this:

javascript
// Create an array to store all the markers
var markers = [];

// Function to create a marker
function createMarker(id, lat, lng) {
var marker = new google.maps.Marker({
position: { lat: lat, lng: lng },
map: map,
draggable: true,
id: id // Store the marker's ID as a property
});

// Add dragend event listener to the marker
google.maps.event.addListener(marker, 'dragend', function() {
var newLat = marker.getPosition().lat();
var newLng = marker.getPosition().lng();

// Call function to update marker in database
updateMarkerInDatabase(marker.id, newLat, newLng);
});

markers.push(marker); // Add the marker to the markers array
}

// Function to update marker in database
function updateMarkerInDatabase(id, lat, lng) {
// Make ajax call to update marker in database using the id, lat, and lng
console.log("Updating marker with ID: " + id + " to new position: " + lat + ", " + lng);
}

// Loop through your data and create markers
for (var i = 0; i < data.length; i++) {
createMarker(data[i].id, data[i].lat, data[i].lng);
}


In this code snippet, we store the marker's ID as a property of the marker object when we create it. Then, in the `dragend` event listener, we can access the marker's ID using `marker.id` and update the marker in the database with the new position.

I hope this helps! Let me know if you have any further questions.

Rate this post

3 of 5 based on 8502 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us