【问题标题】:React Mapbox GL Js - Animate a camera around a pointReact Mapbox GL Js - 围绕一个点为相机设置动画
【发布时间】:2021-07-22 07:27:56
【问题描述】:

我从 Mapbox GL JS 官方文档here 中找到了一个围绕一个点设置相机动画的示例,但它是用纯 Javascript 编写的。

我正在使用 React Js 和 react-map-gl 库,并尝试像上面的示例一样围绕一个点为相机设置动画。

这是我的代码:

import React, { useEffect, useState, useRef } from 'react';
import MapGL, {requestAnimationFrame} from 'react-map-gl';

const [viewport, setViewport] = useState({
    latitude: 40.67,
    longitude: -103.59,
    zoom: 3,
    bearing: 0,
    pitch: 0
});
const mapRef = useRef(null);

const rotateCamera = (timestamp) => {
    mapRef.rotateTo((timestamp / 100) % 360, { duration: 0 })
    requestAnimationFrame(rotateCamera)
}

useEffect(() => {
    rotateCamera(0)
}, [])

return (
      <MapGL 
        {...viewport}
        width="100%"
        height="100%"
        mapStyle={MAP_STYLE}
        onViewportChange={setViewport}
        mapboxApiAccessToken={MAPBOX_TOKEN}
        ref={mapRef}
      />
);

出现编译错误:

Attempted import error: 'requestAnimationFrame' is not exported from 'react-map-gl'.

然后我尝试修复导入:

import MapGL from 'react-map-gl';
import requestAnimationFrame from 'react-map-gl'

但出现运行时错误:

TypeError: mapRef.rotateTo is not a function

那么我该如何正确地实现相机围绕点文档的动画呢?

【问题讨论】:

  • 你应该像这样使用你的参考:mapRef.current.rotateTo(...)。

标签: javascript reactjs mapbox mapbox-gl-js


【解决方案1】:

由于您使用的是 ref,因此您应该使用 mapRef.current

要获取mapbox地图,可以使用getMap()。 所以你可以将地图声明为一个变量:

const map = mapRef.current.getMap(),然后调用rotateTo函数。

也可以直接使用:mapRef.current.getMap().rotateTo(args)

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2019-04-16
    相关资源
    最近更新 更多