/ Published in: jQuery
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Geolocation - Let user choose which result is correct, or auto-assign if only one result is returned.</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="http://github.com/brandonaaron/livequery/raw/master/jquery.livequery.js"></script> <script type="text/javascript"> /* <![CDATA[ */ $(document).ready(function(){ // Hide the result container by default $('div#td_msg').hide(); // Helper function that assigns a value to the target text input box function assignValue(value){ var target = $('input#target'); target.val(value); $('div#td_msg').hide('slow'); } // Geocode the address whenever the input box's value changes $('input#target').change(function() { var dataString = "q=" + $("#target").val().split(" ").join("+") + "&output=json&oe=utf8\&sensor=false&key=ABQIAAAAy9tS-IF2ap3XUdcLPuPSOxQ01e10W64RY7l9Y_lnlyOXiCMlVhTg2tCthvKLlTm5gfHxLY-HjIRkeQ"; var url = "http://maps.google.com/maps/geo?" + dataString; $.getJSON(url + "&callback=?", function(jsonData){ if(jsonData.Placemark.length == 1){ // ....................................... If there's only one result, assignValue(jsonData.Placemark[0].address); // ....................................... assign it to the input box. } else { // ....................................... Otherwise, $('div#td_msg').html('<ul id="results"></ul>'); // ....................................... create a list for the multiple results. $.each(jsonData.Placemark, function(i,result){ // ....................................... For each placemark in the JSON array, we pass its index (i) and value (result), $('ul#results').append('<li class="result">'+result.address+'</li>'); // and then append an item to the results list. }); $('div#td_msg').show('slow'); // ........................................ Then, show the list after it's been populated. } }); }); // Update the input box when a result is clicked // We're using the 'LiveQuery' plugin to gain control over elements added via JSON callbacks $('ul#results li.result').livequery('click',function(){ var thisValue = $(this).text(); assignValue(thisValue); return false; }); }); /* ]]> */ </script> </head> <body> <form action="/" method="post"> <fieldset> <input id="target" type="text" value="Field 1" /> </fieldset> </form> <div id="td_msg"></div> </body> </html>