The ability to drag the Google Maps marker is lost when a custom place is set using Autocomplete

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?

Answer №1

It appears that when you utilize the .setPlace() method of the marker, it becomes non-draggable.

Instead, consider using the .setPosition() method.

replace:

marker.setPlace({
  placeId: place.place_id,
  location: place.geometry.location
});

with:

marker.setPosition(place.geometry.location);

demonstration fiddle

code excerpt:

defaultLatLong = {
  lat: 40.7127753,
  lng: -74.0059728
};

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.setPosition(place.geometry.location);

  currentLatitude = place.geometry.location.lat();
  currentLongitude = place.geometry.location.lng();

});
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="pac-input" />
<div id="map"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Am I using async/await correctly in this code?

Here is the code snippet I am currently working with: var process = async (items: DCXComposite[], session: Session) => { // This function returns a response object with a statusCode property. If the status Code is 200, it indicates a ...

Why is my call to the node.js server not receiving a response?

While using Chrome or Postman, I encountered an issue when sending a simple get request without any parameters. After waiting for 2 minutes, I received an error message instead of the expected response. My expectation was to receive a "cannot get" message ...

Generate a nested object dynamically, assign a specific value, and continue adding more objects using pairs of keys and values

Struggling as a newcomer to JavaScript with nesting values of key-value pairs in an object? Take the example below with Basis, where you need to add nested keys and allocate related values from Basis. Each new object should be wrapped in an array within th ...

Having difficulty creating a snapshot test for a component that utilizes a moment method during the rendering process

I am currently testing a component that involves intricate logic and functionality. Here is the snippet of the code I'm working on: import React, { Component } from 'react'; import { connect } from 'react-redux' import moment from ...

What is the method of utilizing shared services when the controllers do not rely on any shared services?

Let's imagine a scenario where there is a module containing only one factory, which serves as the shared service. angular.module('sharedService', []) .factory('sharedSrv', sharedService) function sharedService() { var numbe ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

Displaying JSON information in an HTML table with JavaScript

I successfully displayed JSON data in an HTML table. Here is the snippet I used: $("#example-table").tabulator({ height:"300px", fitColumns:true, tooltips:true, columns:[ {title:"Month", field:"Month", sorter:"string"}, {title:"Numbers", ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...

Generating a new Blob through assembling MediaRecorder blob sections leads to a blank Blob

I’ve encountered a peculiar issue with the new Blob constructor. My code returns an array of Blobs from the MediaRecorder: https://i.sstatic.net/X8Z7c.png However, when trying to work with this blob in my code, calling new Blob(audioChunks) results in ...

Issues are arising with the .mouseover functionality within this particular code snippet

Learning Javascript has been a challenge for me so far. I tried following a tutorial, but the result I got wasn't what I expected based on the video. I'm wondering why that is and how I can fix it. I'm aiming to make a box appear suddenly w ...

Locating the Smallest Value in an Array of Objects

Looking at an object with keys containing arrays of objects that each have a price value. The goal is to find and return the lowest price value. In this scenario, aiming to return the value 8. Wondering if using the reduce method would be the best approach ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

Error Message "Alexa.create is not a valid function" encountered while using the Alexa HTML Web API on the Echo Show 10

Here is the HTML code for my custom Alexa Skill. <head> <script src="https://cdn.myalexaskills.com/latest/alexa-html.js"> </script> </head> <body> var alexaClient; Alexa.create({version: '1.0'}) .t ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

javascript how to trigger a change or input event when handling a paste event

I have successfully overridden the paste event on the document object, but now I want to trigger the onchange, oninput, and other input events in the event handler for the paste event. document.addEventListener('paste', function (e) { ...

jquery persistently selects element even after altering the class

Having an issue with a button that needs to change its function after meeting a certain condition. I am attempting to select the button by its class, remove that class when the condition is met, add a new class, and then perform another action. However, i ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

What is the impact of sending a JavaScript request to a Rails method every 15 seconds in terms of efficiency?

I have a method that scans for notifications and initiates a js.erb in response. Here is the JavaScript code triggering this method: setInterval(function () { $.ajax({ url: "http://localhost:3000/checkNotification", type: "GET" }); }, 15000); ...

Issue with Angular 5: Bootstrap Tooltip not functioning as expected

Where am I going wrong? I've been attempting to implement a Bootstrap Tooltip in Angular 5, but I'm facing some challenges. We have already set up the Javascript library through the footer of our index.html page as per the recommendations. The B ...