Skip to content

Instantly share code, notes, and snippets.

@k1000
Created August 31, 2011 13:49
Show Gist options
  • Save k1000/1183577 to your computer and use it in GitHub Desktop.
Save k1000/1183577 to your computer and use it in GitHub Desktop.
google maps v3 geocoder
/*
require: jquery
add:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
*/
var Mapper = function( map_canvas, options ){
var map_canvas = document.getElementById(map_canvas || "map_canvas");
this.markersArray = [];
this.infoWindow = new google.maps.InfoWindow();
this.options = {
center: new google.maps.LatLng(28.291564, -16.53913),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.options = $.extend(this.options, options || {});
this.map = new google.maps.Map(map_canvas, this.options);
this.addMarker = function( m_options, center ) {
var that = this;
var marker = new google.maps.Marker( m_options );
marker.setMap(this.map);
if (center) this.map.setCenter(m_options.position);
if (m_options.content){
marker.content = m_options.content;
google.maps.event.addListener(marker, 'click', function() {
that.openInfoWindow(marker);
});
}
this.markersArray.push(marker);
return marker;
};
this.manualGeocode = function( marker, callback ){
google.maps.event.addListener(marker, 'drag', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(marker.getPosition().lat(), marker.getPosition().lng());
}
}
});
});
};
this.clearOverlays = function() {
if (this.markersArray) {
for (var i in this.markersArray) {
this.markersArray[i].setMap(null);
}
}
};
this.codeAddress = function ( address, callback ) {
geocoder = new google.maps.Geocoder();
that = this;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
that.map.setCenter(results[0].geometry.location);
var marker = that.addMarker( {position: results[0].geometry.location, draggable: true });
if (callback !== undefined){
callback(results[0].geometry.location.lat(), results[0].geometry.location.lng());
}
that.manualGeocode(marker, callback);
} else {
alert("Sentimos. No se ha conseguido localizar la dirección: " + status);
}
});
};
this.setCurrentPoint = function( name ){
this.addMarker( { position: this.options.center } );
};
this.openInfoWindow = function(marker, content) {
this.infoWindow.setContent(content || marker.content);
this.infoWindow.open(this.map, marker);
};
this.closeInfoWindow = function() { this.infoWindow.close(); };
// Make the info window close when clicking anywhere on the map.
google.maps.event.addListener(this.map, 'click', this.closeInfoWindow);
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment