geolocationgoogle-api-php-clientweb-development-serverw3c-geolocation

How to work with Google geolocation API?


I'm working on a web development project where I need to get user's exact location information (like Region, City, State, and Country). How do I do that?


Solution

  • You can get this done by using Google's Geocoder and the HTML5 Geolocater. You need to supply Google's Geocoder with an adress or a lat lng, which we will get using the HTML5 Geolocater. I'll show you how to do this, but you can read more about Geocoding below with the link I provided. Anyway, we can get the users lat lng by using the HTML5 Geolocater. Then you can use Google's Geocoder to get the city, state, street, and zip. Here's the steps to do this:

    First, put Google's Geocoder into a variable.

    var geocoder = new google.maps.Geocoder;

    Then grab the user lat lng with the HTML5 Geocoder and use Google's Geocoder to make it into an address.

    if(navigator.geolocation){
    
            // call this function to get the location
    
            navigator.geolocation.getCurrentPosition(function(position) {
    
                // the results return as a lat lng, 
                //which we will put them into a variable to use in Google's Geocoder 
    
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
    
                // Now we can get the location info(city, state, zip) with Google's Geocoder
    
                geocoder.geocode({'location': pos}, function(results, status) {
                    if(status === 'OK'){
                        console.log(results); 
                    }
                });
           });
    }
    

    Then you can do whatever you want with the results. Hope this helps!

    sources: https://developers.google.com/maps/documentation/javascript/geolocation