Mugshot

Hey I'm Lee. My blog was put up to house useful nuggets I could refer back to, document my learning curves on new technologies and house tutorials I write for Umbraco and other .NET stuff.

All thoughts and comments on here are my own, and in no way reflect my employer - I also take no responsibility for spelling, grammar or terminology, so read at your own risk!

Blogs I Read

Sites I Like

An Autocomplete Geocoding Google Map With Draggable Marker

While tinkering and trying to get a Google Map property editor working working for Umbraco v5, I actually ended up writing more JavaScript to get it working - And thought the code is actually pretty useful for any app and not just as an Umbraco DataType.

So what does this actually do?

  1. Has an autocomplete text box that you can either choose from the location results, or just type in a postcode
  2. When you click find it takes the address, postcode whatever and Geocodes it
  3. Then adds a draggable marker on the map and also stores the long & lat in hidden values
  4. If you drag the marker, it saves the new long & lat in the hidden values

goog-map

goo-draggable

HTML / styles

Very simple bit of HTML and some basic styles so you can see the autocomplete dropdown on the textbox, textbox for the address/postcode and a find button. div to show the map and the two hidden inputs to store the long and lats in

        <style>
            .ui-autocomplete {
                background-color: white;
                width: 300px;
                border: 1px solid #cfcfcf;
                list-style-type: none;
                padding-left: 0px; font-family:Arial, Helvetica, sans-serif; cursor:pointer; font-size:12px;
            }
            .ui-menu-item {padding:3px 0;}
        </style>

        <p><input class="postcode" id="Postcode" name="Postcode" type="text"> <input type="submit" id="findbutton" value="Find" /></p>
        
        <div id="geomap" style="width:400px; height:400px;">
            <p>Loading Please Wait...</p>
        </div>
        
        <input id="hidLat" name="hidLat" type="hidden" value="">
        <input id="hidLong" name="hidLong" type="hidden" value="">     

JavaScript

We use the google maps API, Jquery & Jquery UI which we can get from the google CDN. In the initialise method I have added in some default values so when the map first loads it has a marker by default, you can obviously remove all this.

        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>                
        <script type="text/javascript">
        var PostCodeid = "#Postcode";
        var longval = "#hidLong";
        var latval = "#hidLat";
        var geocoder;
        var map;
        var marker;

        function initialize() {
            //MAP
            var initialLat = $(latval).val();
            var initialLong = $(longval).val();
            if (initialLat == '') {
                initialLat = "51.773071843208115";
                initialLong = "-1.6568558468750325";
            }
            var latlng = new google.maps.LatLng(initialLat, initialLong);
            var options = {
                zoom: 16,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
        
            map = new google.maps.Map(document.getElementById("geomap"), options);
        
            geocoder = new google.maps.Geocoder();    
        
            marker = new google.maps.Marker({
                map: map,
                draggable: true,
                position: latlng
            });
        
            google.maps.event.addListener(marker, "dragend", function (event) {
                var point = marker.getPosition();
                map.panTo(point);
            });
            
        };
        
        $(document).ready(function () {
        
            initialize();
        
            $(function () {
                $(PostCodeid).autocomplete({
                    //This bit uses the geocoder to fetch address values
                    source: function (request, response) {
                        geocoder.geocode({ 'address': request.term }, function (results, status) {
                            response($.map(results, function (item) {
                                return {
                                    label: item.formatted_address,
                                    value: item.formatted_address
                                };
                            }));
                        });
                    }
                });
            });
        
            $('#findbutton').click(function (e) {
                var address = $(PostCodeid).val();
                geocoder.geocode({ 'address': address }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        marker.setPosition(results[0].geometry.location);
                        $(latval).val(marker.getPosition().lat());
                        $(longval).val(marker.getPosition().lng());
                    } else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });
                e.preventDefault();
            });
        
            //Add listener to marker for reverse geocoding
            google.maps.event.addListener(marker, 'drag', function () {
                geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0]) {
                            $(latval).val(marker.getPosition().lat());
                            $(longval).val(marker.getPosition().lng());
                        }
                    }
                });
            });
        
        });

    </script>

Just grab all the code above, throw it in a HTML file and open it in your favorite browser and you'll see how it works

Back to top