im creating a route shower with geocoding and reverse geocoding.
Works quite well, but when I want to drag markers I’d like to update proper input with updated address. Problem is I can’t destinguish start and end point. With the following code if i have only 1 point it updates the start address properly, but after adding another point, both of them start to update the same input. (don’t know if i had a good idea to distinguish them by property – i add those points to array, and depending on its lenght it should add property destination with ‘start’ or ‘stop’. Seems like after adding second marker it updates the destination value of previous one).
function placeMarker(location) {
if(list.length < 2) {
marker = new google.maps.Marker({
position: location,
map: map,
draggable:true,
animation: google.maps.Animation.DROP,
destination: 'start'
});
map.setCenter(location);
list.push(marker);
if (list.length == 2) {
list[1].destination = 'stop';
};
geocoder.geocode({'latLng': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
if(list.length == 1) {
$('#start').val(results[0].formatted_address);
} else {
$('#end').val(results[0].formatted_address);
}
}
}
});
}
if (list.length == 2) {
drawRoute(list[0].getPosition(), list[1].getPosition());
};
google.maps.event.addListener(marker, 'drag', function(event) {
console.log(marker.destination);
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker.destination == 'start') {
$("#start").val(results[0].formatted_address);
} else {
$("#end").val(results[0].formatted_address);
}
}
});
});
};
Thank You for help!
You are attaching eventListener to only one marker, instead of
you should do something like
and those listeners should be attached every time marker is created.