Testing Select2 with Google Maps Geocoding API

An example of geocoding and reverse geocoding using Select2 as a nice presentation filter for address results.

HTML

<link rel="stylesheet" href="http://ivaynberg.github.com/select2/select2-3.1/select2.css">
<script src="http://ivaynberg.github.com/select2/select2-3.1/select2.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false&amp;fake-.js"></script>
<input type="hidden" id="test" style="width: 100%" />
<div id="map"></div>
<input type="text" id="latitude" />
<input type="text" id="longitude" />
<input type="text" id="location" />

CSS

#map {
    width: 100%;
    height: 450px;
}
#map img {
    max-width: none;
}

JavaScript

var map, marker, geocoder;
var location = new google.maps.LatLng(52.520816, 13.410186);
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
    zoom: 9,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: location
};

map = new google.maps.Map($('#map')[0], mapOptions);
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
    draggable: true,
    position: location,
    map: map,
    title: "Your location"
});

google.maps.event.addListener(marker, 'dragend', function (event) {
    $('#latitude').val(event.latLng.lat());
    $('#longitude').val(event.latLng.lng());
    reverseGeocode(event.latLng);
});

$("#test").select2({
    placeholder: "Search for a place",
    minimumInputLength: 2,
    query:function(query){
        return geocode(query);
    }
}).on("change", function (e) {
    var res = $("#test").select2("data");
    console.log(res);
    setPosition(res.address);
});

function geocode(query) {
    geocoder.geocode( { 'address': query.term}, function(addresses, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var data = { results: [] };
            for (i = 0; i < addresses.length; i++) {
                data.results.push({
                    id: addresses[i].formatted_address, 
                    text: addresses[i].formatted_address,
                    address: addresses[i]
                });
            }
            return query.callback(data);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

function reverseGeocode(latlng) {
    debugger;
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                setLocation(results[1]);
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });        
}

function setPosition(address) {
    debugger;
    var position...