我的目标是在iOS设备上使用Safari返回我的地理位置坐标。在桌面浏览器上,我正在使用Google Maps Geolocation API key 调用以下函数tryGeolocation()

这适用于台式机Chrome,但在Safari(台式机和iOS)和Chrome(iOS)中,我返回了"Position Unavailable"错误。我尝试了5秒和10秒的超时,但是发生了同样的情况。

是否有已知的解决方法可在iOS中调用Google Maps Geolocation API?

var apiGeolocationSuccess = function(position) {
    alert("API geolocation success!\n\nlat = " + position.coords.latitude + "\nlng = " + position.coords.longitude);
};

var tryAPIGeolocation = function() {
    jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key="MY API KEY", function(success) {
        apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
  })
  .fail(function(err) {
    alert("API Geolocation error! \n\n"+err);
  });
};

var browserGeolocationSuccess = function(position) {
    alert("Browser geolocation success!\n\nlat = " + position.coords.latitude + "\nlng = " + position.coords.longitude);
};

var browserGeolocationFail = function(error) {
  switch (error.code) {
    case error.TIMEOUT:
      alert("Browser geolocation error !\n\nTimeout.");
      break;
    case error.PERMISSION_DENIED:
      if(error.message.indexOf("Only secure origins are allowed") == 0) {
        tryAPIGeolocation();
      }
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Browser geolocation error !\n\nPosition unavailable.");
      break;
  }
};

var tryGeolocation = function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        browserGeolocationSuccess,
      browserGeolocationFail,
      {maximumAge: 50000, timeout: 20000, enableHighAccuracy: true});
  }
};

tryGeolocation();

我是使用iOS浏览器的新手,所以任何建议将不胜感激!

最佳答案

if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
          };
          latt=pos.lat;
          lngg=pos.lng;
          console.log("point :"+latt+","+lngg);
        }, function() {
        });
      } else {
        // Browser doesn't support Geolocation
      }



      this.restapiService.getAllSearchResults()
      .then(data => {

              this.map = new google.maps.Map(this.mapElement.nativeElement, {
                zoom: 100,
                center: {lat: parseFloat(pos.lat), lng: parseFloat(pos.lng)}
              });

        var position = new google.maps.LatLng(parseFloat(pos.lat), parseFloat(pos.lng));
        var sMarker = new google.maps.Marker({position: position,animation: google.maps.Animation.DROP, title: "My Location"});
        sMarker.setMap(this.map);
      });
    }

您可以尝试获取当前位置[在iOS上进行测试(浏览器模拟器, ionic 型)]

10-08 05:46
查看更多