I am currently working on developing a Custom Google Map that allows the user to select a position either through input with autocomplete suggestions or by dragging the marker on the map.
Interestingly, I have noticed that when I create a map without the autocomplete feature, the marker remains draggable. However, as soon as I integrate the autocomplete listener, the marker loses its draggable functionality after using the autocomplete feature once.
Below is the JavaScript code snippet that I am utilizing:
defaultLatLong = {lat: xxxx lng: xxxx};
var map = new google.maps.Map(document.getElementById('map'), {
center: defaultLatLong,
zoom: 13,
mapTypeId: 'roadmap'
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var marker = new google.maps.Marker({
map: map,
position: defaultLatLong,
draggable: true,
clickable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
currentLatitude = latLng.lat();
currentLongitude = latLng.lng();
var latlng = {lat: currentLatitude, lng: currentLongitude};
var geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
input.value = results[0].formatted_address;
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location
});
currentLatitude = place.geometry.location.lat();
currentLongitude = place.geometry.location.lng();
});
Are there any suggested solutions to address this particular issue?