How to get the location name of a dragged marker?

In the following example, I show how to get the location name when the marker is dragged and dropped by the user on Google maps.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY=initMap" async></script>

<script type="text/javascript">
    function initMap() {
        var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
        var mapOptions = {
            zoom: 4,
            center: myLatlng
        }
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        //Create a marker
        marker = new google.maps.Marker(
            {
                map: map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: myLatlng,
            });

        google.maps.event.addListener(marker, 'dragend', function () {
            geocodePosition(marker.getPosition());
        });

        //Callback function of the drag event.
        function geocodePosition(pos) {
            geocoder = new google.maps.Geocoder();
            geocoder.geocode
                ({
                    latLng: pos
                },
                    function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK)
                            console.log(results[0].formatted_address);
                        else
                            console.log('Cannot determine address at this location.' + status);
                    }
                );
        }
    }

</script>

First the geocodePosition callback function is added, which will be called whenever the marker was dragged. In this function the position of the marker is decoded into a location name using the Geocoder from Google Maps Geocoding service.

Leave a Reply