3

我有一个 JSON:http ://maps.googleapis.com/maps/api/geocode/json?latlng=49,19&sensor=false

我只需要得到国家的短名称。(对于这个例子'SK')。因此,我得到了属性“types”包含[“country”,“political”]的short_name。

我有...

 data.results[0].address_components

谢谢。

4

3 回答 3

18

这将遍历地址组件并查找国家类型然后是政治。如果您只想在两者都出现的情况下返回该国家/地区,请告诉我。虽然修改这段代码并不难,因为主要的帮助点是for循环。

// extract country short name (e.g. GB for Great Britain) from google geocode API result
function getCountry(addrComponents) {
    for (var i = 0; i < addrComponents.length; i++) {
        if (addrComponents[i].types[0] == "country") {
            return addrComponents[i].short_name;
        }
        if (addrComponents[i].types.length == 2) {
            if (addrComponents[i].types[0] == "political") {
                return addrComponents[i].short_name;
            }
        }
    }
    return false;
}

console.log(getCountry(data.results[0].address_components));
于 2013-10-08T12:47:57.610 回答
1
<?php
$address = '77-379 North End road, London London SW61NP, United Kingdom'; // Your address(Please USe exist address)
$prepAddr = str_replace(' ','+',$address);

$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=API_KEY&sensor=false');
$output= json_decode($geocode);


if ( isset($output->results) ) {
    if ( isset($output->results[0]) ) {
        if ( isset($output->results[0]->address_components) ) {
            foreach ($output->results[0]->address_components as $key => $value) {   
                if ( isset($value->types) ) {
                    if ( isset($value->types[0]) ) {
                        if($value->types[0] == 'country'){
                            print_r($value->short_name); //GB
                        }
                    }
                }
            }
        }
    }
} ?>
于 2017-12-08T18:34:38.843 回答
0

这个是找地址,城市名,省的

200 Dufferin St, 多伦多, ON

geocoder.geocode(function (responses) {
    res = responses[0].address_components[0].short_name.concat(' ')
        .concat(responses[0].address_components[1].short_name).concat(', ')

    for (var i = 0; i < responses[0].address_components.length; i++) {
        if (responses[0].address_components[i].types[0] == "locality") {
            res = res.concat(responses[0].address_components[i].short_name).concat(', ');
        }
    }

    for (var i = 0; i < responses[0].address_components.length; i++) {
        if (responses[0].address_components[i].types[0] == "administrative_area_level_1") {
            res = res.concat(responses[0].address_components[i].short_name);
        }
    }
    alert(res);
});
于 2018-06-18T19:17:46.130 回答