Maps API v3 Marker fits to defined bounds

by upsidown

HTML

<script src="http://maps.google.com/maps/api/js?sensor=false&amp;.js"></script>
<div id="map"></div>

CSS

html, body {
    height:100%;
}
#map {
    width:100%;
    height: 100%;
}

JavaScript

var center = new google.maps.LatLng(32.3985, -3.6914);
var bounds = new google.maps.LatLngBounds();
var boundsSet = false;
var lastPosition = center;

var map = new google.maps.Map(document.getElementById('map'), {
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    zoom: 5
});

google.maps.event.addListener(map, 'bounds_changed', function () {

    if (!boundsSet) {
        bounds = map.getBounds();
        boundsSet = true;
        console.log(bounds);
    }
});

var marker = new google.maps.Marker({
    map: map,
    position: center,
    draggable: true
});

google.maps.event.addListener(marker, 'dragend', function () {

    var position = marker.getPosition();
    bounds.contains(position) ? lastPosition = position : marker.setPosition(lastPosition);
});