So I have an interactive map that adds an initial marker when it's loaded. Every time the user moves that marker, it records and updates the location (longitude & latitude) of the marker in a text field.
What I want to do now is to add an onclick event so that when the user clicks somewhere else on the map, a new marker shows up (and delete the initial one), then update the location.
I played around with onclick listener, clear marker with setMapOnAll method, but no success. I know I'm missing something but i dont know what. Below is my functionnal code that only allow populating the marker, dragable, but not onclick. PLEASE HELP:
<div id="map" style="height: 500px;"> </div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
// fill in the fields with the marker position
function updateMarkerPosition(latLng) {
document.getElementById('pdb-longitude').value = latLng.lng();
document.getElementById('pdb-latitude').value = latLng.lat();
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(49.691219873776326, -112.83338917980956);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Location successfully Recorded ! Fill in the form below');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="infoPanel">
<b>Location status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
</div>