如何根据JavaScript中的地理定位显示不同的图像?

时间:2014-10-23 21:03:26

标签: javascript html5 geolocation show

function getLocation()
    { if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(doRequest);
    }
}
function getCountry(addrComponents){
    for (var i = 0; i < addrComponents.length; i++){
        if (addrComponents[i].types[0] == "country") {
        return addrComponents[i].short_name;
    }
}
    return false;
}

function doRequest(position) {

    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&sensor=false', true);

xhr.onload = function (){

        var data = JSON.parse(this.responseText);
        if (data.results.length > 0) {
            console.log(getCountry(data.results[0].address_components));
        } };

        xhr.send();
    }


        window.onload = getLocation();

0 个答案:

没有答案