Search code examples
reactjsgeolocationlatitude-longitudegoogle-geolocation

How to get position (latitude and longitude) from a postal (zip) code in react?


I need to know what is the best way to get latitude and longitude from a postal (zip) code in react ?

I try with geocode from google API (with the npm package react-geocode), but I can't do a search based on only the postal code.

So I need your opinion on how to do that. Example of sources code will be also appreciate.

Thank you in advance for all your comments. Regards...


Solution

  • Maybe try something like this and adjust it to your needs as only few context is given:

     var lat = '';
     var lng = '';
    
    // depends on whether you really only have the zip code
     var address = {zipcode} or {city and state};
    
     geocoder.geocode({ 'address': address}, function(results, status) {
       if (status == google.maps.GeocoderStatus.OK) {
          lat = results[0].geometry.location.lat();
          lng = results[0].geometry.location.lng();
         });
       } else {
         console.log("Geocode was not successful for the following reason: " + status);
       }
     });
     console.log('Latitude: ' + lat + ' Longitude: ' + lng);