How to get latitude and longitude from Autocomplete without showing the map with Google Maps API and JavaScript?

Sometimes, we want to get latitude and longitude from Autocomplete without showing the map with Google Maps API and JavaScript.

In this article, we’ll look at how to get latitude and longitude from Autocomplete without showing the map with Google Maps API and JavaScript.

How to get latitude and longitude from Autocomplete without showing the map with Google Maps API and JavaScript?

To get latitude and longitude from Autocomplete without showing the map with Google Maps API and JavaScript, we can use the getPlace method.

For instance, we write

const initialize = () => {
  const input = document.getElementById("searchTextField");
  const autocomplete = new google.maps.places.Autocomplete(input);
  google.maps.event.addListener(autocomplete, "place_changed", function () {
    const place = autocomplete.getPlace();
    document.getElementById("city2").value = place.name;
    document.getElementById("cityLat").value = place.geometry.location.lat();
    document.getElementById("cityLng").value = place.geometry.location.lng();
  });
};

google.maps.event.addDomListener(window, "load", initialize);

to define the initialize function.

In it, we create an autocomplete input with

const autocomplete = new google.maps.places.Autocomplete(input);

Then we get the autocomplete value when we type on it by listening toi the place_changed event with addListener.

Next, we get the place with getPlace.

And then we get the name of the place and its latitude and longitude with lat and lng.

Conclusion

To get latitude and longitude from Autocomplete without showing the map with Google Maps API and JavaScript, we can use the getPlace method.