反向地理编码v3

时间:2015-10-04 06:58:32

标签: javascript google-maps google-maps-api-3

我无法使用此代码。我正在做的是使用地理位置获取设备的lat和lng值,将其保存在变量pos中并且它可以工作。我可以在警报窗口中查看值。我无法工作的是反向地理编码。它不会使用变量pos。

中的值返回任何地址
<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 50%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>


<script>
var pos=[];
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 16
  });



  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };


      alert(position.coords.latitude+" "+position.coords.longitude);

      geocodeLatLng(geocoder, map, infowindow);

      map.setCenter(pos);
    }, 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.');
}


function geocodeLatLng(geocoder, map, infowindow) {

  geocoder.geocode({'location': pos}, function(results, status) {

    if (status === google.maps.GeocoderStatus.OK) {

      if (results[1]) {

        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: pos,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);

        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
        async defer>
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
    async defer>
</script>

您正在异步加载API,在回调运行之前(initMap运行之前和之后,而不是之前)不能使用API​​

代码段

var pos = [];
var geocoder;
var infoWindow;
var map;

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

  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      // alert(position.coords.latitude + " " + position.coords.longitude);

      geocodeLatLng(geocoder, map, infoWindow, pos);

      map.setCenter(pos);
    }, 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.');
}

function geocodeLatLng(geocoder, map, infowindow, pos) {
  document.getElementById('info').innerHTML = pos.lat.toFixed(6) + "," + pos.lng.toFixed(6);
  geocoder.geocode({
    'location': pos
  }, function(results, status) {

    if (status === google.maps.GeocoderStatus.OK) {

      if (results[0]) {

        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: pos,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);

        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 50%;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<div id="info"></div>
<div id="map"></div>