Get map while typing address and get address by dragging marker in google maps

Suppose you have a contact form with a input field called location or address. Now you want to show user his or her location in google maps based on address he or she typed. Or you need their location co-ordinate (latitude and longitude) for that address. To convert addresses into geographic coordinates and geographic coordinates to address google maps has Geocoding API. Full documentation for Geocoding API is here https://developers.google.com/maps/documentation/geocoding/. To use this API you might need a api key.

If you are interested you can click here to see what we are going to do.

Lets start with the HTML and CSS. First we need to create a input field and a container for the map. In this post we’ll also create two input field for latitude and longitude. In real world scenario you might want these two fields to be hidden.

<div class="wrapper">
    <label for="location">Type Location Here : <input type="text" name="location" id="location" /></label>
    <label for="lat">Lat : <input type="text" name="lat" id="lat" /></label>
    <label for="lng">lng : <input type="text" name="lng" id="lng" /></label>
    <div id="map-canvas" class="hidden"></div>
</div>
.wrapper { width: 800px; }
.hidden { display: none; }
#map-canvas { height: 300px; margin: 10px 0; }

Please note that we kept the map container hidden.

That’s all we need to do with HTML and CSS. Now we’ll move to JS part. We’ll use jQuery here as our javascript library.
Now add jQuery and google maps library into your HTML head

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;sensor=false"></script>

Now we need to initialize map and marker object. First we will set our map center at 0,0 co-ordinate.

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 16
    },
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions),
    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: 'Drag to set position',
        draggable: true,
        flat: false
    });

Google maps Geocoding API provides multiple set results for a address. When user types the address we’ll take that address as a string and make a ajax request to geocoding api and use the first result to show the map. Do not forget to resize the map after shown. To resize all we need to do is trigger resize event.

//get location from address
    $('#location').keyup(function() {
        if ($('#map-canvas').hasClass('hidden')) {
            $('#map-canvas').removeClass('hidden').fadeIn().addClass('show');
            google.maps.event.trigger(map, 'resize');
        }
        var address = $(this).val();
        if (address.length == 0) {
            $('#map-canvas').removeClass('show').fadeOut().addClass('hidden');
        }
        url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false';
        $.get(url, function(data) {
            if (data.status == 'OK') {
                map.setCenter(data.results[0].geometry.location);
                marker.position=map.getCenter();
                $('#lat').val(data.results[0].geometry.location.lat);
                $('#lng').val(data.results[0].geometry.location.lng);

            }
        });
    });

If you want your user to set address from the map by dragging the marker on the map you can also do that by using Geocoding API. This api also provides address from co-ordinate. Now we’ll do just the opposite to what we have done before.

google.maps.event.addListener(marker, 'dragend', function() {
        latlng = marker.getPosition();
        url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+ latlng.lat() + ',' + latlng.lng() + '&sensor=false';
        $.get(url, function(data) {
            if (data.status == 'OK') {
                map.setCenter(data.results[0].geometry.location);                
                if (confirm('Do you also want to change location text to ' + data.results[0].formatted_address) === true) {
                    $('#location').val(data.results[0].formatted_address);
                    $('#lat').val(data.results[0].geometry.location.lat);
                    $('#lng').val(data.results[0].geometry.location.lng);
                }
            }
        });
        
    });

That’s all. You can get the full code here http://jsfiddle.net/dct2spzt/5/. Thank you for reading the post.