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

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

When I use `console.log` with `req.body` in Node, the password is

Currently, I am utilizing NodeJs on the backend to console.log(req.body) data from a form that gathers usernames and passwords from users. I have noticed that this method exposes the collected username and password information. Should I be concerned abou ...

How to arrange a collection of objects in JavaScript

I am facing a challenge with sorting the array based on the address._id field of each object. Despite attempting to use the lodash orderby function, I have not been able to achieve the desired outcome. [{ rider_ids: '5b7116ea3dead9870b828a1a& ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

Newbie mishap: Utilizing an array retrieved from a function in javascript/jquery

After submitting the form, I call a function called getPosts and pass a variable str through it. My aim is to retrieve the data returned from the function. // Triggered upon form submission $('form#getSome').submit(function(){ var str = $("f ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Is there a method in CSS animations that allows for endlessly repeating successive animations in a specified sequence?

While working with CSS animations, I encountered a challenge of making two animations occur successively and repeat infinitely without merging keyframes. Is there a way to achieve this using only CSS? If not, how can I accomplish it using JavaScript? I a ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

What could be causing the appearance of sha256.js when making an AJAX request to a PHP script using jQuery?

Currently, I am executing a script that saves modifications to a PHP script in the background using jquery-ajax. Additionally, I have implemented a function that triggers an error if the script attempts to post something on the site. In case of an error, I ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Demonstrate a array of values at varying angles within a circle using the functionalities of HTML5 canvas

Looking to utilize HTML5 Canvas and Javascript for a project where I need to showcase various values (depicted by dots possibly) at different angles within a circle. For example, data could include: val 34% @ 0°, val 54% @ 12°, val 23% @ 70°, a ...

If the option is not chosen, remove the requirement for it

I am in the process of creating a form that offers 3 different payment options: 1 - Direct Deposit 2 - Credit Card 3 - Cash at Office The issue I am facing is with the validation of input fields for Credit Cards. I want to make it so that these field ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

What are the reasons behind the lack of smooth functionality in the Bootstrap 4 slider?

My customized bootstrap4 slider is functional, but lacks smoothness when clicking on the "next" and "prev" buttons. The slider transitions suddenly instead of smoothly. Any suggestions on how to fix this? Here is the code for the slider: $('.carous ...

What could be causing my React Router component to display incorrect styling?

While working with react-router, I encountered an issue where the text from the routed page started appearing in the navbar. Even though I separated it as its own component and it functions correctly, this specific problem persists. As a newcomer to React, ...

Using javascript to dynamically change text color depending on the selected item

I am currently working on a website for a snow cone stand and I want to incorporate an interactive feature using JavaScript. Specifically, I would like to color code the flavor list based on the actual fruit color. The flavor list is already structured i ...

When a radiobutton is clicked, a jQuery call to a PHP function triggers an AJAX request which results in a JavaScript function becoming unrefer

Currently, I have a situation where two radio buttons are representing different products. When one of them is clicked, the goal is to update the price displayed on the website based on the selected product. Everything seems to be working fine when using t ...

Refreshing a webpage using AJAX from a different URL of a secondary web service

I am working on a page that retrieves data from a specific web service URL. I am conducting some processing involving a multiple choice checkbox, and I want the same page to reload and fetch its data from a second web service with a different URL to retrie ...

Web Security Vulnerability: Cross Site Scripting Detected

In our code, we are aiming to prevent XSS (Cross Site Scripting) attacks. However, the solution may involve a combination of JS (JavaScript) and HTML escaping, which could prove to be quite challenging. Below is a snippet that closely resembles our code: ...

Once the recursive function executes (utilizing requestAnimationFrame), socket.emit can finally be triggered

My current issue involves sending an array to my server from the client side using a recursive function, but the responses from the server are delayed and only arrive after the recursive function completes. I'm uncertain whether the problem lies with ...