/ Published in: JavaScript
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Initialize a googlemap with a single marker * Dragging the marker updates a text input * * usage: * $('#map').('#myinput', -41.3, 174.783); * * requirements: * googlemaps script to be loaded with your googlemaps api key * <code> * <script src="http://maps.google.com/maps/api/js?sensor=false&key=YOURKEY"></script> * </code> * * @param input string selector for the input to update * @param lat float latititude for the marker * @param lng float longitude for the marker * */ (function ($) { $.fn.googlemap = function (input, lat, lng) { var el = this.eq(0); return el.each(function () { var latlng = new google.maps.LatLng(lat, lng); var options = { zoom: 14, mapTypeControl: false, scrollwheel: false, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(this, options); var marker = new google.maps.Marker({ position: latlng, map: map, draggable: true }); geocoder = new google.maps.Geocoder(); google.maps.event.addListener(marker, "dragend", function () { geocoder.geocode({ latLng: marker.getPosition() }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { $(input).val(results[0].formatted_address) } } }) }) }) } })(jQuery);