Reputation: 63
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!
Upvotes: 4
Views: 15989
Reputation: 678
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.
Upvotes: 2
Reputation: 2879
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
)
Upvotes: 4