Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I need to make use of google maps api using php so that I can display information on my database matching the users Zip code/Postal Code detected by the google api. Can I have a sample code for this please?

I am able to get the postal code of the user using Ajax, Json and Javascript. However I don't know how I could pass this data into the backend php. I tried many solutions, but I'm still unable to get the data into the backend. The following is my code.







<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Google Maps GeoCoding</title>
  </head>
  <body>
    <header>
      <h1>Reverse GeoCoding with Google Maps</h1>
    </header>
    <p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>
    <!-- write some stuff about a place here -->
    <script>
    var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {

      const KEY = "hidden";
      const LAT = position.coords.latitude;
      const LNG = position.coords.longitude;
      let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${LAT},${LNG}&key=${KEY}`;
      fetch(url)
        .then(response => response.json())
        .then(data => {
          console.log(data);
          let parts = data.results[0].address_components;
         
          parts.forEach(part => {
           
            if (part.types.includes("postal_code")) {
              document.body.insertAdjacentHTML(
                "beforeend",
                `<p>PostalCode: ${part.long_name}</p>`
              );
            }  
          });
        })
        .catch(err => console.warn(err.message));
}
    </script>
  </body>
</html>


What I have tried:

I have tried using javascript - json. I am completely new to jason so I find things difficult there as to how to pass the data into the backend php.
Posted
Updated 8-Oct-21 4:52am
v4
Comments
Richard MacCutchan 8-Oct-21 7:18am    
"I don't know what I'm doing wrong."
Nor do we, since you have not told us what the problem is.
Tyler Gutmann 8-Oct-21 7:31am    
Sorry, I want to pass the Json data (Postal Code) into php. How can I achieve this?
Chris Copeland 8-Oct-21 9:55am    
You had code on here previously and now you've removed it, why? Providing us with code gives us some context where we can provide advice, without it we can't know what you have and haven't tried.
Tyler Gutmann 8-Oct-21 10:19am    
Sorry, I have added my code again. Hope my question is clear enough. Thank you.

1 solution

As the page has finished loading there's no way to retroactively get the Geolocation data direct within the screen, instead your best bet would be to issue a separate AJAX request to send the information you need to another PHP page, one built to accept the information.

JavaScript
let parts = data.results[0].address_components;

// You have the array of address components here so either serialise
// them into a JSON object or process each one individually and send
// an AJAX request here to your other PHP page.
fetch('/path/to/page.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(parts)
})
.then(result => console.log('Sent to the other PHP page!'));
         
parts.forEach(part => {
           
  if (part.types.includes("postal_code")) {
    document.body.insertAdjacentHTML(
      "beforeend",
      `<p>PostalCode: ${part.long_name}</p>`
    );
  }
});
 
Share this answer
 
Comments
Tyler Gutmann 8-Oct-21 14:17pm    
Yes, I'm getting the success message! Thank you so much. Can I know how I can access the passed details in the next page. Sorry I'm new to this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900