获取用户国家和城市名称并在 google 地图上定位

Get user country and city name and locate on google map

我想在 google 上显示用户的当前位置和国家名称、城市名称映射我尝试显示国家和城市名称未定义的代码,如何在 [=14= 上显示国家和城市名称] 地图

<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>

您需要对从地理定位服务返回的位置进行反向地理编码以获取国家和城市信息。

 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"
        // 
        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"
            // 
            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

代码片段:

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"
            // 
            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"
                // 
                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>