jerry
jerry

Reputation: 59

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?

Upvotes: 0

Views: 710

Answers (2)

Kamlesh
Kamlesh

Reputation: 6135

<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  </head>
  <body>
  <div id="navbar"><span>Geolocation API</span></div>
  <div id="wrapper">
    <button id="location-button">Get User Location</button>
    <div id="output"></div>
  </div>

  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXYOURXXGOOGLEXXAPIXXKEYXXXX&libraries=places"></script>
  <script>
          $('#location-button').click(function(){

            var location_address_arr = Array();
            var location_address = '';
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position){
                  console.log(position);

                    var lat = position.coords.latitude;
                    var lng = position.coords.longitude;
                    var latlng = new google.maps.LatLng(lat, lng);
                    var geocoder = geocoder = new google.maps.Geocoder();
                    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                          // console.log(results);
                          if(results.length > 0){
                            var place = results[0];

                            var city_long_name = '';

                            var client_company_city = '';
                            var client_company_state = '';
                            var client_company_country = '';
                            var client_company_postal_code = '';

                            for (var i = 0; i < place.address_components.length; i++) {
                                var addressType = place.address_components[i].types[0];
                                var long_name = place.address_components[i].long_name;
                                // alert(addressType);

                                if(city_long_name==''){
                                    if(addressType=='postal_town'){
                                        // city
                                        city_long_name = place.address_components[i].long_name;

                                    } else if (addressType=='administrative_area_level_1'){
                                        // city                
                                        city_long_name = place.address_components[i].long_name;

                                    } else if (addressType=='locality'){
                                        // city
                                        city_long_name = place.address_components[i].long_name;
                                    }
                                }

                                if(addressType=='administrative_area_level_1'){
                                    // state
                                    client_company_state = long_name;
                                }
                                if(addressType=='country'){
                                    // country
                                    client_company_country = long_name;
                                }
                                if(addressType=='postal_code'){
                                    // postal_code
                                    client_company_postal_code = long_name;
                                }
                                // 
                            }
                            client_company_city = city_long_name;

                            // city
                            if(client_company_city!=''){
                              location_address_arr.push(client_company_city);
                            }

                            // state
                            if(client_company_state!=''){
                              location_address_arr.push(client_company_state);
                            }

                            // country
                            if(client_company_country!=''){
                              location_address_arr.push(client_company_country);
                            }

                            // zipcode
                            if(client_company_postal_code!=''){
                              location_address_arr.push(client_company_postal_code);
                            }

                            if(location_address_arr.length > 0){
                              location_address = location_address_arr.join(', ');
                            }
                            alert(location_address);

                          }
                        }
                    });

                });

            }

          });
  </script>
  </body>
</html>

Upvotes: 0

James Madison
James Madison

Reputation: 26

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

Upvotes: 1

Related Questions