How to get city name from latitude and longitude in phone gap?
Asked Answered
B

6

11

I am able to get get full address from current latitude and longitude. but how can I get only city name from full address. this is my code.

var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
//alert("Else loop" + latlng);
geocoder.geocode({
    'latLng': latlng
}, function(results, status) {
    //alert("Else loop1");
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
            var add = results[0].formatted_address;
            alert("Full address is: " + add);
        } else {
            alert("address not found");
        }
    } else {
        //document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
        //alert("Geocoder failed due to: " + status);
    }
});
Briolette answered 28/3, 2014 at 5:36 Comment(1)
possible duplicate of How do I get location name or city using latitude & longitudes?Professional
B
15
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);

geocoder.geocode(
    {'latLng': latlng}, 
    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    alert("city name is: " + city);
                }
                else  {
                    alert("address not found");
                }
        }
         else {
            alert("Geocoder failed due to: " + status);
        }
    }
);

Split the full address with "," as delimiter and get the city name..

Briolette answered 28/3, 2014 at 9:50 Comment(0)
S
6

Clean example to get location from lat and lang and parsing result. based on Google Reverse Geocoding

 var geocodingAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=23.714224,78.961452&key=YOUR_SERVER_API_KEY";

 $.getJSON(geocodingAPI, function (json) {
     if (json.status == "OK") {
         //Check result 0
         var result = json.results[0];
         //look for locality tag and administrative_area_level_1
         var city = "";
         var state = "";
         for (var i = 0, len = result.address_components.length; i < len; i++) {
             var ac = result.address_components[i];
            if (ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.short_name;
         }
         if (state != '') {
             console.log("Hello to you out there in " + city + ", " + state + "!");
         }
     }

 });
Staples answered 13/1, 2015 at 11:1 Comment(1)
How are you finding city in this code? I think it should be through administrative_area_level_2Rothermere
C
2

You can find documentation here :

https://developers.google.com/maps/documentation/geocoding/?hl=fr#ReverseGeocoding

But you can see in your "results" which item is the city without spliting the object.

So you can do :

country=results[0]['address_components'][6].long_name;
state=results[0]['address_components'][5].long_name;
city=results[0]['address_components'][4].long_name;

Be carefull, the numbers "4,5,6" can change by the country. So it safier to test like that :

Getting street,city and country by reverse geocoding using google

Cantal answered 28/3, 2014 at 11:40 Comment(0)
D
1

Take a look at Google Reverse Geocoding

http://maps.google.com/maps/api/geocode/xml?latlng=YourLatitude,YourLongitude&sensor=false&key=API_KEY

This is already asked here

Diapophysis answered 28/3, 2014 at 8:40 Comment(0)
G
1

This is how I I'm doing it. Was afraid to use a comma delimiter.

function ReverseGeoToCity(lat, lng, callback) {
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
            var properName = ", ";

            for(i=0; i<results[1].address_components.length; i++){
                if (results[1].address_components[i].types[0] == "locality")
                    properName = results[1].address_components[i].short_name + properName;
                if (results[1].address_components[i].types[0] == "administrative_area_level_1")
                    properName += results[1].address_components[i].short_name;
            }

            callback(properName);
      } else {
          alert('No results found');
      }
    } else {
        alert('Geocoder failed due to: ' + status);
    }
    });
}
Gingras answered 9/6, 2015 at 3:2 Comment(0)
F
0

Below code will help you for get city name From latitude and longitude:

 var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key=KEY_HERE&sensor=false";
        $.get(url, function(data) {
        var results = data.results;
            if (data.status === 'OK') 
            {
                //console.log(JSON.stringify(results));
                if (results[0]) 
                {
                    var city = "";
                    
                   var address_components = results[0].address_components;
                    
                    for (var i = 0; i < address_components.length; i++) 
                    {  state = address_components[i].long_name;    
                        }
                        if (address_components[i].types[0] === "locality" && address_components[i].types[1] === "political" ) {                                
                            city = address_components[i].long_name;   
                        }
                    }
                    alert("CITY : " + city );
               } 
               else 
               {
                   window.alert('No results found');
               }
            } 
            else 
            {
                window.alert('Geocoder failed due to: ' + status);
            
            }
        });
Fogbow answered 6/3, 2022 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.