javascriptgoogle-mapsreverse-geocoding

How do I get address by given lat/long


How do I get address by given lat/long not location? I have tried with "Reverse Geocoding" but it's showing only the location name.

My code is this:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
var marker;
var marker2;

function initialize() {
geocoder = new google.maps.Geocoder();
var
latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
    zoom: 5,
    center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function (event) {
    //alert(event.latLng);      
    geocoder.geocode({
        'latLng': event.latLng
    }, function (results, status) {
        if (status ==
            google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                alert(results[1].formatted_address);
            } else {
                alert('No results found');
            }
        } else {
            alert('Geocoder failed due to: ' + status);
        }
    });
}); <!--click event--> }
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>


Solution

  • Address with street number is at index 0. Use

    results[0].formatted_address
    

    instead of

    results[1].formatted_address
    

    And you will get the address

    For example, at index 0 you get: "36 Osborne Street, Wollongong ...", at index 1 you get "Wollongong Hospital Crown St, Wollongong ...".

    You can get components of formatted_address using

    results[0].address_components[0]
    ...
    results[0].address_components[5]