How can I get city name from a latitude and longitude point?

后端 未结 11 1204
感情败类
感情败类 2020-11-28 03:07

Is there a way to get a city name from a latitude and longitude point using the google maps api for javascript?

If so could I please see an example?

11条回答
  •  执笔经年
    2020-11-28 03:23

    Here's a modern solution using a promise:

    function getAddress (latitude, longitude) {
        return new Promise(function (resolve, reject) {
            var request = new XMLHttpRequest();
    
            var method = 'GET';
            var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
            var async = true;
    
            request.open(method, url, async);
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        var data = JSON.parse(request.responseText);
                        var address = data.results[0];
                        resolve(address);
                    }
                    else {
                        reject(request.status);
                    }
                }
            };
            request.send();
        });
    };
    

    And call it like this:

    getAddress(lat, lon).then(console.log).catch(console.error);
    

    The promise returns the address object in 'then' or the error status code in 'catch'

提交回复
热议问题