使用Google Maps API将纬度和经度转换为街道地址

时间:2015-12-31 05:53:23

标签: javascript

根据纬度和经度,如何使用Google Maps JavaScript API将其转换为街道地址?

1 个答案:

答案 0 :(得分:2)

以下是我们在Javascript中的操作。确保您有互联网连接:),将您的纬度和经度传递给displayLocation function.try此网址

google map response

function displayLocation(latitude, longitude) {
            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 && request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var address = data.results[0];
                    var value = address.formatted_address.split(",");
                    count = value.length;
                    country=value[count-1];
                    state = value[count - 2];
                        city = value[count - 3];
                    alert(city);
                    // document.write(address.formatted_address);

                }
            };
            request.send();
        };

        var successCallback = function(position) {
            var x = position.coords.latitude;
            var y = position.coords.longitude;
            displayLocation(x, y);
        };

        var errorCallback = function(error) {

        };

        var options = {
            enableHighAccuracy : true,
            timeout : 1000,
            maximumAge : 0
        };

        navigator.geolocation.getCurrentPosition(successCallback, errorCallback,
                options);

        }