Guest User

Untitled

a guest
May 7th, 2013
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 2.07 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
  5. <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  6. <title>Reverse Geocoding</title>
  7.  
  8. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
  9. <script type="text/javascript">
  10.   var geocoder;
  11.  
  12.   if (navigator.geolocation) {
  13.     navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  14. }
  15. //Get the latitude and the longitude;
  16. function successFunction(position) {
  17.     var lat = position.coords.latitude;
  18.     var lng = position.coords.longitude;
  19.     codeLatLng(lat, lng)
  20. }
  21.  
  22. function errorFunction(){
  23.     alert("Geocoder failed");
  24. }
  25.  
  26.   function initialize() {
  27.     geocoder = new google.maps.Geocoder();
  28.  
  29.  
  30.  
  31.   }
  32.  
  33.   function codeLatLng(lat, lng) {
  34.  
  35.     var latlng = new google.maps.LatLng(lat, lng);
  36.     geocoder.geocode({'latLng': latlng}, function(results, status) {
  37.       if (status == google.maps.GeocoderStatus.OK) {
  38.       console.log(results)
  39.         if (results[1]) {
  40.          //formatted address
  41.          alert(results[0].formatted_address)
  42.         //find country name
  43.              for (var i=0; i<results[0].address_components.length; i++) {
  44.            for (var b=0;b<results[0].address_components[i].types.length;b++) {
  45.  
  46.            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
  47.                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
  48.                    //this is the object you are looking for
  49.                    city= results[0].address_components[i];
  50.                    break;
  51.                }
  52.            }
  53.        }
  54.        //city data
  55.        alert(city.short_name + " " + city.long_name)
  56.        } else {
  57.          alert("No results found");
  58.        }
  59.      } else {
  60.        alert("Geocoder failed due to: " + status);
  61.      }
  62.    });
  63.  }
  64. </script>
  65. </head>
  66. <body onload="initialize()">
  67.  
  68. </body>
  69. </html>
Advertisement
Add Comment
Please, Sign In to add comment