Home > other >  Why localStorage not getting data from autocomplete?
Why localStorage not getting data from autocomplete?

Time:12-27

I save the entered data in the input field in localStorage. If you enter text data from the keyboard or simply paste the copied text, then this data gets into localStorage. But if you select a text from a hint, then only the text that was typed on the keyboard gets into localStorage, for example, the first letter of the city, but the selected city and hints do not

What's wrong?

<input type="text" name="input6" id="input6" value="" placeholder="Enter destination" autocomplete="off">

document.addEventListener('DOMContentLoaded', function() {
 let input2 = document.querySelector('[name="input6"].large');

 if (input2) {
   input2.value = localStorage.getItem("movingto") || "";

    input2.addEventListener('input', function() {
      localStorage.setItem("movingto", this.value);
    });
 }
});

const center = { lat: 50.064192, lng: -130.605469 };
const defaultBounds = {
  north: center.lat   0.1,
  south: center.lat - 0.1,
  east: center.lng   0.1,
  west: center.lng - 0.1,
};

const input5 = document.getElementById("input6");
const options = {
  bounds: defaultBounds,
  componentRestrictions: { country: "us" },
  fields: ["address_components", "geometry", "icon", "name"],
  strictBounds: false,
  types: ["establishment"],
};

const autocomplete2 = new google.maps.places.Autocomplete(input5, options);

https://jsfiddle.net/Sacred13/umwe9301/2/

CodePudding user response:

I'm not an expert in maps API, but it seems that the autocomplete doesn't actually trigger input event on the input, so you could add another listener for when the autcomplete is actually triggered by adding place_changed event to the autocomplete instance.

Basically just add this code at the bottom:

autocomplete2.addListener("place_changed", () => {
  let input2 = document.querySelector('[name="input6"].large');
  if (input2) {
    localStorage.setItem("movingto", input2.value);
  }
});

here's the fiddle fork: https://jsfiddle.net/26zyfpqk/

CodePudding user response:

According to google maps documentation there is a place_changed event which you should use instead of native input event you are using.

So this would look like this in your case:

autocomplete.addListener("place_changed", () => {
    const place = autocomplete.getPlace();
    console.log({ place });
    // It will log "place" object which contains all useful info you can use (including full address).
})
  • Related