Obtener el nombre del país a partir de la latitud y la longitud

I have a latitude and a longitude, and I need to fetch country.

Estoy usando esto:

$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$deal_lat.",".$deal_long . "&sensor=false");
$output_deals = json_decode($geocode_stats);
$country = $output_deals->results[2]->address_components[4]->long_name;

Sometimes it gives a correct country name, but sometimes it gives blank values, and sometimes it returns a city name.

¿Alguien puede ayudar?

preguntado el 14 de enero de 13 a las 06:01

So give us the example urls that don't behave explicitly. PS: "its urgent" never helps -

With the code you assume that the result will always be in the same place. However, with the way the results are structured, you may have 0 or more results each with 1 or more address components. The country may not be always in result 2 or adress_component 4. But you can search the result arrays for the country field. -

6 Respuestas

I wrote a function to make it easy. Simply pass in your geo-address which can be a full address, zip code, or in your case latitude and longitude. It will then search through the address component array for the country. In the case that it is unable to find the county it will simply return null, you can change that to an empty string ("") if you need to.

function getGeoCounty($geoAddress) {
    $url = 'http://maps.google.com/maps/api/geocode/json?address=' . $geoAddress .'&sensor=false'; 
    $get     = file_get_contents($url);
    $geoData = json_decode($get);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \InvalidArgumentException('Invalid geocoding results');
    }

    if(isset($geoData->results[0])) {
        foreach($geoData->results[0]->address_components as $addressComponent) {
            if(in_array('administrative_area_level_2', $addressComponent->types)) {
                return $addressComponent->long_name; 
            }
        }
    }
    return null; 
}

Respondido 15 ago 14, 21:08

Get complete Address from latitude and longitude.

$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
$json = @file_get_contents($url);$data=json_decode($json);
echo $data->results[0]->formatted_address;

respondido 26 nov., 14:08

$deal_lat=30.469301;

$deal_long=70.969324;

$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$deal_lat.','.$deal_long.'&sensor=false');

$output= json_decode($geocode);

for($j=0;$j<count($output->results[0]->address_components);$j++){

    $cn=array($output->results[0]->address_components[$j]->types[0]);

    if(in_array("country", $cn)){
        $country= $output->results[0]->address_components[$j]->long_name;
    }
}

echo $country;

Respondido 05 ago 15, 11:08

It is simple code if you need to find city name then replace in_array("country", $cn) to in_array("locality", $cn) if you need to find Zip code then replacein_array("country", $cn) to in_array("postal_code", $cn). - Patel áspero

$deal_lat=30.469301;
$deal_long=70.969324;
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$deal_lat.','.$deal_long.'&sensor=false');

$output= json_decode($geocode);

for($j=0;$j<count($output->results[0]->address_components);$j++){

    $cn=array($output->results[0]->address_components[$j]->types[0]);

    if(in_array("country", $cn)){
        $country= $output->results[0]->address_components[$j]->long_name;
    }
}

echo $country;

Respondido 05 ago 15, 11:08

how can i get the city? - Mohamed Abrar Ahmed

I did take the code of matwonk as base.

function getGeoCounty($geoAddress) {
    $url = 'http://maps.google.com/maps/api/geocode/json?address=' . urlencode($geoAddress) .'&sensor=false'; 
    $get     = file_get_contents($url);
    $geoData = json_decode($get);
    if(isset($geoData->results[0])) {
        $return = array();
        foreach($geoData->results[0]->address_components as $addressComponet) {
            if(in_array('political', $addressComponet->types)) {
                if($addressComponet->short_name != $addressComponet->long_name)
                    $return[] = $addressComponet->short_name. " - " . $addressComponet->long_name; 
                else
                    $return[] = $addressComponet->long_name; 
            }
        }
        return implode(", ",$return);
    }
    return null;
}

The code return in format: neighborhood, City, State, Country

if detect a shortname (as country code or state code) appear in format CODE - NAME.

contestado el 04 de mayo de 14 a las 01:05

        $latlng = '22.7314,75.88243';
        $request_url = "http://maps.googleapis.com/maps/api/geocode  /xml?latlng=".$latlng."&sensor=true";
        $xml = simplexml_load_file($request_url);

        if($xml->status == "OK") {
        $address = $xml->result->formatted_address;
          foreach ($xml->result->address_component as $address) {
            if("country" ==  trim($address->type)) {
              $country = $address->short_name;
            }
          }
        }

Respondido 23 ago 17, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.