get city from location html

Solutions on MaxInterview for get city from location html by the best coders in the world

showing results for - "get city from location html"
Luciana
12 Jun 2018
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;
16function successFunction(position) {
17    var lat = position.coords.latitude;
18    var lng = position.coords.longitude;
19    codeLatLng(lat, lng)
20}
21
22function 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
57
58        } else {
59          alert("No results found");
60        }
61      } else {
62        alert("Geocoder failed due to: " + status);
63      }
64    });
65  }
66</script> 
67</head> 
68<body onload="initialize()"> 
69
70</body> 
71</html>