React.js 地理位置在 iPhone/Android 浏览器中不起作用

问题描述

我正在尝试在地图上获取我的位置,它在我的计算机上的 Google Chrome 浏览器上运行良好,但是当模拟到 android/iPhone 时,例如在 iPhone 模拟器上使用自定义位置时没有任何反应。在我的实际 iPhone 上也尝试过,但没有任何运气。 我能在模拟器/真实设备上找到的所有接受位置的设置都处于开启状态

GoogleMap.js

import React from 'react'
import GoogleMapReact from 'google-map-react'
import {usePosition} from "./usePosition";

const defaultProps = {
    center: {
        lat: 10.0000000,lng: 12.0000000,},zoom: 18.7,}
const MeOnMap = ({ text }) => <div className="me-on-map"><img src="static/walking.gif" width="30" /></div>
const GoogleMap = () => {
    const { latitude,longitude} = usePosition();
    return (
    <div style={{ marginLeft: '-17px',height: '528px',width: '109%' }}>
        <GoogleMapReact
            bootstrapURLKeys={{ key: '*********' }}
            defaultCenter={defaultProps.center}
            defaultZoom={defaultProps.zoom}
            yesIWantToUseGoogleMapApiInternals
            options={{ scrollwheel: false,zoomControl: false,fullscreenControl: false,gestureHandling: 'none',styles: [{ stylers: [{ 'saturation': 100 },{ 'gamma': 0.5 }]}] }}
        >
            <MeOnMap
                lat={latitude}
                lng={longitude}
                text={''}
            />
        </GoogleMapReact>
    </div>
)}

export default GoogleMap

geo.js

import React from 'react';
import {usePosition} from './usePosition';
export const UsePositions = () => {
    const {latitude,longitude} = usePosition();
    return (
        <code>
            My position,<br/>
            latitude: {latitude}<br/>
            longitude: {longitude}<br/>
        </code>
    );
};

usePosition.js

import {useState,useEffect} from 'react';

const defaultSettings = {
    enableHighAccuracy: false,timeout: Infinity,maximumAge: 0,};

export const usePosition = (watch = false,settings = defaultSettings) => {
    const [position,setPosition] = useState({});
    const [error,setError] = useState(null);

    const onChange = ({coords,timestamp}) => {
        setPosition({
            latitude: coords.latitude,longitude: coords.longitude,accuracy: coords.accuracy,speed: coords.speed,timestamp,});
    };

    const onError = (error) => {
        setError(error.message);
    };

    useEffect(() => {

        if (!navigator || !navigator.geolocation) {
            setError('Geolocation is not supported');
            return;
        }

        let watcher = null;
        if (watch) {
            watcher =
                navigator.geolocation.watchPosition(onChange,onError,settings);
        } else {
            navigator.geolocation.getCurrentPosition(onChange,settings);
        }

        return () => watcher && navigator.geolocation.clearWatch(watcher);

    },[
        settings.enableHighAccuracy,settings.timeout,settings.maximumAge,]);

    return {...position,error};
};

有人知道哪里出了问题吗? 谢谢!!

解决方法

没关系,如果不是从安全连接收集到的位置被阻止

Origin does not have permission to use Geolocation service -- even over HTTPS

通过使用 --https 运行 npm 解决了