如何使用 HTML5 地理位置找到用户所在的国家/地区?

2022-01-14 00:00:00 geolocation javascript html

我熟悉用于返回用户位置粗略坐标的 HTML5 地理位置.

I'm familiar with HTML5 geolocation for returning rough coordinates of the user’s location.

但是,我怎样才能返回他们坐标所在国家的名称?

However, how can I return the name of the country that their coordinates are in?

推荐答案

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': <YOURLATLNGRESPONSEFROMGEO>}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                }
            }
        });

    function getCountry(results)
    {
        for (var i = 0; i < results[0].address_components.length; i++)
        {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/s/gi, '').length < 1;
}

这是我用的:)

相关文章