Autocomplétion api google maps
Dans cet article, nous allons voir comment mettre en place fenêtre modale avec Jquery-ui avec une autocomplétion grâce à l’api de google maps. Le rendu voulu est une case à cocher « visible sur la map », le fait de cocher la case ouvre une fenêtre modale avec la map ainsi que le champs d’autocomplétion.
Prérequis
- Jquery
- Jquery-ui
- Api Google Maps
<html> <head> <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.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script> <link rel="stylesheet" media="screen" type="text/css" href="../jquery-ui/css/ui-lightness/jquery-ui-1.8.14.custom.css" /> <script type="text/javascript"> $(document).ready(function(){ $('#map').click(function() { var geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(48.86607,2.353706); var options = { zoom: 5, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var marker; var map; var item; if($('#map').attr('checked')) { $('#dialogMap').dialog({ width: 850, height: 580, modal: true, open: function(event, ui) { map = new google.maps.Map(document.getElementById("map_canvas"), options); marker = new google.maps.Marker({ map: map, draggable: false }); }, buttons: { 'Valider': function() { $('#dialogMap').dialog('destroy'); }, 'Annuler': function() { if($('#map').is(':checked')) { $('#map').attr('checked', false); $.uniform.update('#map'); } $('#dialogMap').dialog('destroy'); } }, close: function() { if($('#map').is(':checked')) { $('#map').attr('checked', false); $.uniform.update('#map'); } $('#dialogMap').dialog('destroy'); } }); } $(function() { $('#geolocation').autocomplete({ 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, latitude: item.geometry.location.lat(), longitude: item.geometry.location.lng() } })); }); }, select: function(event, ui) { item = ui.item; var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude); marker.setPosition(location); map.setCenter(location); } }); }); }); }); </script> </head> <body> <form> <label for="map">Visible sur la carte</label> <input type="checkbox" name="map" id="map" /> </form> <div id="dialogMap" title="Localisation" style="display:none;"> <form> <label for="geolocation">Adresse: </label> <input type="text" name="geolocation" id="geolocation" size="33" /> </form> <div id="map_canvas" style="width:850px;height:580px;"></div> </div> </body> </html> |
Et voila, relativement simple et efficace
.