shukerullah / react-geocode

A React module to transform a description of a location (i.e. street address, town name, etc.) into geographic coordinates (i.e. latitude and longitude) and vice versa.
MIT License
207 stars 35 forks source link

How to get only the city? #34

Closed ferdiamg closed 3 years ago

ferdiamg commented 4 years ago

If I access the results like the following:

getLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        Geocode.setApiKey(API_KEY);
        Geocode.setLanguage("de");
        Geocode.setRegion("de");
        Geocode.fromLatLng(
          position.coords.latitude,
          position.coords.longitude
        ).then(response => {
            const address = response.results[0].formatted_address;
            ...

I get this as an outcome for San Francisco: SFLO, Van Ness Ave, San Francisco, CA 94102, USA and for Berlin I get this: B2 7, 10178 Berlin, Deutschland

How can I access ONLY the city in that way for users from many different locations? Thats almost impossible, since even a regex can't work on a non-deterministic outcome.

If I access the whole response object, theres still no option to ONLY get the city: image

shukerullah commented 4 years ago

@ferdiamg Did you find solution?

subhajitpanja commented 3 years ago

I have almost same query, I need city state country separately

nadesh-git commented 3 years ago

Had a similar requirement and made a workaround for it.Try this solution on this pull request

shukerullah commented 3 years ago

@nadesh-git Thanks for the solution and PR.

Here is example to get city, state and country.

const apiKey = "API_KEY_GOES_HERE";
const language = "de";
const region = "de";
const locationType = "ROOFTOP";

let city, state, country;

Geocode.fromLatLng(
  "48.8583701",
  "2.2922926",
  apiKey,
  language,
  region,
  locationType
).then(
  (response) => {
    for (let i = 0; i < response.results[0].address_components.length; i++) {
      for (let j = 0; j < response.results[0].address_components[i].types.length; j++) {
        switch (response.results[0].address_components[i].types[j]) {
          case "locality":
            city = response.results[0].address_components[i].long_name;
            break;
          case "administrative_area_level_1":
            state = response.results[0].address_components[i].long_name;
            break;
          case "country":
            country = response.results[0].address_components[i].long_name;
            break;
        }
      }
    }
    console.log(city, state, country);
  },
  (error) => {
    console.error(error);
  }
);