Retrieve the place_id associated with the address components

Having trouble obtaining the place_id of address_components using Google place autocomplete? The JSON data only includes long_name, short_name, and types. Take a look at my code snippet below:

var object_location = document.getElementById('object_location'),
    autoComplete = new google.maps.places.Autocomplete(object_location);

autoComplete.addListener('place_changed', function() {
   var place = autoComplete.getPlace();
   console.log('place = ', place);
});

Check out my JSON data here.

I'm not interested in the place_id of my place. Instead, I specifically need the place_ids of address_components.

Answer №1

If you perform reverse geocoding on the result, it will provide detailed results for each address component that encompasses that specific location.

autoComplete.addListener('place_changed', function() {
  var place = autoComplete.getPlace();
  map.setZoom(11);
  var marker = new google.maps.Marker({
    position: place.geometry.location,
    map: map
  });
  infowindow.setContent(place.formatted_address);
  infowindow.open(map, marker);
  geocoder.geocode({
      latLng: place.geometry.location
    },
    function(results, status) {
      if (status === 'OK') {
        console.log("revGeo result=" + JSON.stringify(results));
        var htmlStr = "<table border='1'>";
        for (var i = 0; i < results.length; i++) {
          htmlStr += "<tr><td>" + results[i].formatted_address + "</td><td>" + results[i].place_id + "</td></tr>";
        }
        htmlStr += "</table>";
        infowindow.setContent(infowindow.getContent() + "<br>" + htmlStr);
      } else {
        window.alert('Geocoder failed due to: ' + status);
      }
    });
});

validation of idea fiddle

snippet of code:

var geocoder;
var map;
var infowindow;

function initialize() {
  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow();
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var object_location = document.getElementById('object_location'),
    autoComplete = new google.maps.places.Autocomplete(object_location);

  autoComplete.addListener('place_changed', function() {
    var place = autoComplete.getPlace();
    map.setZoom(11);
    var marker = new google.maps.Marker({
      position: place.geometry.location,
      map: map
    });
    infowindow.setContent(place.formatted_address);
    infowindow.open(map, marker);
    geocoder.geocode({
        latLng: place.geometry.location
      },
      function(results, status) {
        if (status === 'OK') {
          var htmlStr = "<table border='1'>";
          for (var i = 0; i < results.length; i++) {
            htmlStr += "<tr><td>" + results[i].formatted_address + "</td><td>" + results[i].place_id + "</td></tr>";
          }
          htmlStr += "</table>";
          infowindow.setContent(infowindow.getContent() + "<br>" + htmlStr);
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
      });
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  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="object_location" />
<div id="map_canvas"></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

Switch positions of two objects in JavaScript

Check out the code snippet below: MyObject.prototype.doIt = function() { let a = this.obj1; let b = this.obj2; } I need to find a way to switch the values of this.obj1 and this.obj2, making obj1 take on the value of obj2 and vice versa. Pleas ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Issue with npm during installation of REACT - not functioning as expected

After executing all the necessary commands on the command line, including globally installing npm with npm install -g create-react-app, as well as running npx create-react-app <myprojectname> and clearing the npm cache, I consistently encountered an ...

Error: The node is unable to parse JSON data through the API

After loading a JSON file as a string, attempting to parse it back to JSON and send it as a response: router.get('/todos', (req,res) =>{ let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{ if (err) ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Angular JS: How to dynamically add and remove checkboxes in ng-repeat?

Currently, I have successfully implemented a Miller column using Angular and Bootstrap. To view the functionality in action, you can check out the code snippet at this link. In the second column of my setup, clicking on a word opens up the third column. ...

What is the best way to create a keyup event for the entire document except for one specific element?

Looking for some advice on how to handle a specific code scenario. Here's what I have: $(document).ready(function(){ $(document).on("keyup",function(e){myFunction(e)}); }); function myFunction(e){ console.log("hi"); } In ...

jQuery - can you identify which specific object from the entire set this is?

I am curious if there is a simple method to identify which DOM object I have when it is also part of another set of objects. To illustrate, let's consider the following scenario: There are 5 div elements: <div id="1"></div> <div id="2 ...

Navigating with React Router using server-side routing in the web browser

I'm currently developing a web application that utilizes react on the client side and express on the server side. For routing the client pages, I've been using react-router (link). Initially, I had success using hashHistory, but now I want to ...

Using MUI Select with Array of Objects for values - Learn how to deselect a predefined state

I have a list of objects structured like this: [ { _id: "6311c197ec3dc8c083d6b632", name: "Safety" }, ........ ]; These objects are loaded as Menu Items options for my Select component: {categoryData && c ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

Implementing the loading of a Struts 2 action with jquery in javascript

Looking to refresh a specific div using JavaScript with jQuery to target the div and a Struts action that loads the content. Can anyone offer advice on how to achieve this? The challenge lies in utilizing JavaScript and jQuery for this task. Best regards ...

What modifications can be made to the code in order to show the upload progress for each individual file when uploading multiple files simultaneously?

I am currently working on an uploader that can handle multiple file uploads and displays the progress of each uploaded file. However, I am facing some difficulties in showing the progress of every individual file. Can anyone provide me with assistance? &l ...

"Using JavaScript to find and manipulate objects within an array by either removing them or adding

I'm struggling to manipulate an array by either removing or adding an object based on its existence. I've attempted using both a for if loop and forEach loop but haven't been successful. Here's my current approach: // Object in ...

I am seeking assistance to utilize Flexbox to completely fill the height of my computer screen

Seeking assistance in utilizing Flexbox to occupy 100% of my computer screen's height, all while ensuring responsiveness: View of my current sign-in page on Chrome (Note the whitespace): Examining my existing frontend code: const SignIn = () => { ...

Suggestions for improving the smoothness of the Bootstrap toggle hide/show feature

Recently completed my bootstrap toggle hide/show feature and everything seems to be functioning correctly, except for the transition between the different contents. The borders appear jagged and not smooth when activating the toggle. I suspect there may b ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

If I use npm install to update my packages, could that cause any conflicts with the code on the remote server?

As I navigate through the numerous issues, I stumbled upon the command npm ci that is supposed to not change the package-lock.json file. However, when I attempt to run npm ci, it fails: ERR! cipm can only install packages when your package.json and package ...