0

I want to show user's current location and country name,city name on google map the code which I tried showing undefined for country and city name ,how to show country and city name on google map

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMnYWXbdpKU3t__MXrRMLAMer23E6gRjs"></script>
<script type="text/javascript">
if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function (p) {

        var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        console.log(LatLng);
        var mapOptions = {
            center: LatLng,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        console.log(map); 
        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude+"<br/>Country:"+p.coords.country+"<br/>city:"+p.coords.city
        });
        google.maps.event.addListener(marker, "click", function (e) {
            var infoWindow = new google.maps.InfoWindow();
            infoWindow.setContent(marker.title);
            infoWindow.open(map, marker);
        });
    });
} else {
    alert('Geo Location feature is not supported in this browser.');
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
user_1234
  • 741
  • 1
  • 9
  • 22
  • 1
    you need to geocode the lat/long using some geocoding API ... the browser does NOT supply that information for you in the callback to `navigator.geolocation.getCurrentPosition` - to see what the browser does give you, read [the documentation for the [position object](https://developer.mozilla.org/en-US/docs/Web/API/Position) and the coordinates property of the aforementioned position object](https://developer.mozilla.org/en-US/docs/Web/API/Coordinates) - there is no city/country property as you can see – Jaromanda X Jul 23 '19 at 08:55
  • what would you like the code to do? use googles documented geocoding API to determine the city/country of a given latitude/longitude? Or perhaps you can just read the code on googles own example https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse – Jaromanda X Jul 23 '19 at 08:58
  • 1
    What does `console.log(p.coords);` output? An object. Does it have a `country` and a `city` key? No. So how do you expect `p.coords.city` to output the city name?? – MrUpsidown Jul 23 '19 at 09:01
  • + to answer your *"please write some code for me"* request: Please show that you have done some research first. Please read the documentation, and please don't expect people to code for you. – MrUpsidown Jul 23 '19 at 09:03

1 Answers1

0

You need to reverse geocode the position returned from the Geolocation service to get the country and city information.

 geocoder.geocode({
    'location': LatLng
  }, function(results, status) {
    console.log("geocoder callback status=" + status);
    if (status === 'OK') {
      if (results[0]) {
        map.setZoom(11);
        // from "Google maps API, get the users city/ nearest city/ general area"
        // https://stackoverflow.com/questions/50081245/google-maps-api-get-the-users-city-nearest-city-general-area
        var details = results[0].address_components;
        var city;
        var country;
        console.log(JSON.stringify(details));
        for (var i = details.length - 1; i >= 0; i--) {
          for (var j = 0; j < details[i].types.length; j++) {
            if (details[i].types[j] == 'locality') {
              city = details[i].long_name;
            } else if (details[i].types[j] == 'sublocality') {
              city = details[i].long_name;
            } else if (details[i].types[j] == 'neighborhood') {
              city = details[i].long_name;
            } else if (details[i].types[j] == 'postal_town') {
              city = details[i].long_name;
              console.log("postal_town=" + city);
            } else if (details[i].types[j] == 'administrative_area_level_2') {
              city = details[i].long_name;
              console.log("admin_area_2=" + city);
            }
            // from "google maps API geocoding get address components"
            // https://stackoverflow.com/questions/50225907/google-maps-api-geocoding-get-address-components
            if (details[i].types[j] == "country") {
              country = details[i].long_name;
            }
          }
        }
        console.log("city=" + city);
        var marker = new google.maps.Marker({
          position: LatLng,
          map: map,
          title: "<div style = 'height:80px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude + "<br/>Country:" + country + "<br/>City:" + city
        });
        google.maps.event.addListener(marker, "click", function(e) {
          var infoWindow = new google.maps.InfoWindow();
          infoWindow.setContent(marker.title);
          infoWindow.open(map, marker);
        });
        google.maps.event.trigger(marker, 'click');
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('dvMap'), {
    zoom: 8,
    center: {
      lat: 40.731,
      lng: -73.997
    }
  });
  var geocoder = new google.maps.Geocoder();
  var infowindow = new google.maps.InfoWindow();
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(p) {
      var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
      console.log(LatLng);
      var mapOptions = {
        center: LatLng,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map.setOptions(mapOptions);
      geocoder.geocode({
        'location': LatLng
      }, function(results, status) {
        console.log("geocoder callback status=" + status);
        if (status === 'OK') {
          if (results[0]) {
            map.setZoom(11);
            // from "Google maps API, get the users city/ nearest city/ general area"
            // https://stackoverflow.com/questions/50081245/google-maps-api-get-the-users-city-nearest-city-general-area
            var details = results[0].address_components;
            var city;
            var country;
            console.log(JSON.stringify(details));
            for (var i = details.length - 1; i >= 0; i--) {
              for (var j = 0; j < details[i].types.length; j++) {
                if (details[i].types[j] == 'locality') {
                  city = details[i].long_name;
                } else if (details[i].types[j] == 'sublocality') {
                  city = details[i].long_name;
                } else if (details[i].types[j] == 'neighborhood') {
                  city = details[i].long_name;
                } else if (details[i].types[j] == 'postal_town') {
                  city = details[i].long_name;
                  console.log("postal_town=" + city);
                } else if (details[i].types[j] == 'administrative_area_level_2') {
                  city = details[i].long_name;
                  console.log("admin_area_2=" + city);
                }
                // from "google maps API geocoding get address components"
                // https://stackoverflow.com/questions/50225907/google-maps-api-geocoding-get-address-components
                if (details[i].types[j] == "country") {
                  country = details[i].long_name;
                }
              }
            }
            console.log("city=" + city);
            var marker = new google.maps.Marker({
              position: LatLng,
              map: map,
              title: "<div style = 'height:80px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude + "<br/>Country:" + country + "<br/>City:" + city
            });
            google.maps.event.addListener(marker, "click", function(e) {
              var infoWindow = new google.maps.InfoWindow();
              infoWindow.setContent(marker.title);
              infoWindow.open(map, marker);
            });
            google.maps.event.trigger(marker, 'click');
          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
      });
    });
  } else {
    alert('Geo Location feature is not supported in this browser.');
  }
}
html,
body,
#dvMap {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="dvMap"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
geocodezip
  • 158,664
  • 13
  • 220
  • 245