【问题标题】:How to get the webshim polyfill library working in React?如何让 webshim polyfill 库在 React 中工作?
【发布时间】:2019-06-25 09:57:51
【问题描述】:

我想从 webshim 库中访问地理定位功能,但我没有找到正确的设置来让它工作?

我已经在访问内置的浏览器 geolocation 功能,但想在没有 geolocation 功能的浏览器的情况下设置 polyfill。

webshim


    import React from "react";
    import webshim from 'webshim';
    import $ from 'jquery';

    class PlayGround extends React.Component{

        pickLocation = () => {
            console.log("Inside here")
                webshim.ready('geolocation', () => {
                    navigator.geolocation.getCurrentPosition(function(pos){
                    alert("Thx, you are @ latitude: "+ pos.coords.latitude +"/longitude: " + pos.coords.longitude);
                });
              });
        console.log("end inside")
        }
    }

【问题讨论】:

  • 不确定React,但在React Native 中它不起作用。你可以在 react native 中使用geolocation。
  • @TejashwiKalpTaru 我实际上只想在 React 中使用它 - 我想使用 polyfill 作为无法访问内置地理定位功能的浏览器的替代方案。 (我已经修改了问题)

标签: reactjs webshim


【解决方案1】:

使用 polyfill 来填充对地理位置的支持将不起作用。从浏览器获取位置需要原生支持。

几乎所有浏览器都支持地理定位,https://caniuse.com/#feat=geolocation

相反,您应该检查浏览器是否支持地理定位。如果不支持,请优雅地失败(向用户显示一些错误)

function fetchLocation() {
    var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };
    navigator.geolocation.getCurrentPosition(success, error, options);
}

function success(pos) {
    var crd = pos.coords;
    console.log('Your current position is:');
    console.log(`Latitude : ${crd.latitude}`);
    console.log(`Longitude: ${crd.longitude}`);
    console.log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
}


if(window.location.protocol == "https:" && navigator.geolocation) {
    fetchLocation();
} else {
    // We cannot access the geolocation, show some error
}

【讨论】:

  • 这是一个更好的方法
猜你喜欢
  • 1970-01-01
  • 2014-12-19
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多