简体   繁体   中英

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

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);
    }
});
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..

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 + "!");
         }
     }

 });

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

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

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);
    }
    });
}

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);
            
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM