简体   繁体   English

iOS Safari 上 javascript 中的地理定位

[英]Geolocation in javascript on iOS Safari

My objective is to return the coordinates of my geolocation using Safari on an iOS device.我的目标是在 iOS 设备上使用 Safari 返回我的地理位置坐标。 On my desktop browser, I am calling the function tryGeolocation() below with a Google Maps Geolocation API key.在我的桌面浏览器上,我使用 Google Maps Geolocation API 密钥调用下面的函数tryGeolocation()

This works on desktop Chrome, but in Safari (Desktop and iOS) and Chrome (iOS) I am returned the "Position Unavailable" error.适用于桌面 Chrome,但在 Safari(桌面和 iOS)和 Chrome (iOS) 中,我返回"Position Unavailable"错误。 I have tried with a 5 and 10 second timeout, but the same happens.我尝试过 5 秒和 10 秒的超时,但同样发生了。

Is there a known workaround for calling the Google Maps Geolocation API in iOS?在 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();

I am new to working with iOS browsers so any suggestions would be appreciated !!我是 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);
      });
    }

You can try this to get current position [tested on iOS (Browser emulator-ionic)]你可以试试这个来获得当前位置[在 iOS (Browser emulator-ionic) 上测试]

Try without third parameter of getCurrentPosition() since we have issue on error.POSITION_UNAVAILABLE.尝试不使用 getCurrentPosition() 的第三个参数,因为我们在 error.POSITION_UNAVAILABLE 上有问题。

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);
      }
    };

    tryGeolocation();

Here is the example with Permissions and Navigation APIs involved这是涉及权限导航API 的示例

Remember, it works ONLY IF the host is using HTTPS .请记住,它在主机使用HTTPS 时才有效 That may the cause of the permission alert not showing up due to your comment to an answer below.由于您对以下答案的评论,这可能是权限警报未显示的原因。

Remember if your host does not use HTTPS, it will timeout to an error about authentication failure.请记住,如果您的主机不使用 HTTPS,它将超时并显示身份验证失败的错误。 Use error callback to check that.使用错误回调来检查。

 if ( navigator.permissions && navigator.permissions.query) { //try permissions APIs first navigator.permissions.query({ name: 'geolocation' }).then(function(result) { // Will return ['granted', 'prompt', 'denied'] const permission = result.state; if ( permission === 'granted' || permission === 'prompt' ) { _onGetCurrentLocation(); } }); } else if (navigator.geolocation) { //then Navigation APIs _onGetCurrentLocation(); } function _onGetCurrentLocation () { const options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; navigator.geolocation.getCurrentPosition( function (position) { //use coordinates const marker = { lat: position.coords.latitude, lng: position.coords.longitude }; }, function (error) { //error handler here }, options) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM