从用户当前位置获取县/市/州

时间:2017-06-12 04:31:51

标签: html5 google-maps

我正在网站上构建一个新页面,我需要根据用户访问该页面的位置访问用户县/城市/州信息。应用程序使用Html5,可以使用google maps api或其他任何方式来实现,如果可以的话,请提供一些有关示例实现的指示。

1 个答案:

答案 0 :(得分:0)

您可以在Google Maps JavaScript API文档中查看地理位置示例:

https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

您应该添加反向地理编码以获取城市,州和国家/地区。以下代码片段应该可以解决这个问题



var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 6
        });
        infoWindow = new google.maps.InfoWindow;
        var geocoder = new google.maps.Geocoder;

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            
            geocoder.geocode({'location': pos}, function(results, status) {
            if (status === 'OK') {
              if (results[0]) {
                var filtered_array = results[0].address_components.filter(function(address_component){
                  return address_component.types.includes("country");
                }); 
                var country = filtered_array.length ? filtered_array[0].long_name: "";
                filtered_array = results[0].address_components.filter(function(address_component){
                  return address_component.types.includes("locality");
                }); 
                var locality = filtered_array.length ? filtered_array[0].long_name: "";
                filtered_array = results[0].address_components.filter(function(address_component){
                  return address_component.types.includes("administrative_area_level_1");
                }); 
                var admin_area = filtered_array.length ? filtered_array[0].long_name: "";
                
                
                infoWindow.setContent('Location found.<br/>City:'+locality+'<br/>State:'+admin_area+'<br/>Country:'+country);
                infoWindow.setPosition(pos);
                infoWindow.open(map);
                map.setCenter(pos);
              } else {
                window.alert('No results found');
              }
            } else {
              window.alert('Geocoder failed due to: ' + status);
            }
            });   
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
&#13;
#map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
&#13;
<div id="map"></div>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
    </script>
&#13;
&#13;
&#13;