4

Im trying to write a function that will give return latitude and longitude from a zip code. I am attempting to use google maps api to do this.

I am seeing that geocoder seems to be good for this but I am struggling to know how to use it. What im looking to do is use a function to return a passed in zip code to return as an array with the latitude and longitude coordinates.

I created an account to get an API key. For example lets say my function is:

function getCoordinates (zipcode);

How can I write this out so that passed in zipcode would return the lat and long? Thanks for any responses!

John
  • 73
  • 1
  • 1
  • 6
  • The geocoder is asynchronous, you can't return it's result from a function (at least without a callback or a promise) – geocodezip Oct 12 '18 at 01:49
  • Im running into that issue now. Im getting a error originated either by throwing inside of an sync function without a catch block,, or by rejecting a promies which was not handled with .catch(). Im going to start looking into what exactly that means. Thanks for the heads up! If anyone wants to break it down what that means that would be great too! – John Oct 12 '18 at 03:09
  • https://stackoverflow.com/search?q=user%3A1210329+geocoder+asynchronous – geocodezip Oct 12 '18 at 03:27

2 Answers2

3

You're right, geocoding api is what you need. Basically you have to perform a get request to

https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ZIP&key=YOUR_API_KEY

You also may want to specify a country for search. To achieve this, just add region param with country code (for example region=us)

Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27
2

If you're asking how to get the data from the API call, given that you already have the part where you define the address parameter and where you actually call the function, hopefully this will help:

function getCoordinates(address){
  fetch("https://maps.googleapis.com/maps/api/geocode/json?address="+address+'&key='+API_KEY)
    .then(response => response.json())
    .then(data => {
      const latitude = data.results.geometry.location.lat;
      const longitude = data.results.geometry.location.lng;
      console.log({latitude, longitude})
    })
}

I am not entirely sure if you can get the longitude and latitude parameters by ZIP code, or only by address and/or region, but its worth a try. Here's a link to the docs for the Google Maps API. Hope this helps.

Petar
  • 539
  • 5
  • 14
  • Yeah im very new to javascript so not sure how the fetch command works. Basically what https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ZIP&key=YOUR_API_KEY gives is a URL that has a "location" property. Im trying to figure out how I can make a function to return the lat and lng components from the location object. – John Oct 12 '18 at 02:13