繁体   English   中英

react-mapbox-gl _onClickGeolocate() 调用 setTimeout 自动请求位置

[英]react-mapbox-gl _onClickGeolocate() call with setTimeout to request location automatically

我正在使用以下代码将GeolocateControl添加到我的 react-mapbox-gl 地图中。

我需要使用setTimeout()自动调用方法_onClickGeolocate方法以在加载页面时自动请求用户位置。

我怎么能做到这一点?

import { Component } from "react";
import PropTypes from "prop-types";
import { accessToken } from "../../api/tokens/mapbox";
import mapboxgl from "mapbox-gl";

class Locater extends Component {
  static contextTypes = { map: PropTypes.object.isRequired };
  componentDidMount() {
    const { map } = this.context;

    map.addControl(
      new mapboxgl.GeolocateControl({
        accessToken,
        positionOptions: {
          enableHighAccuracy: true
        },
        trackUserLocation: true
      })
    );
  }

  render() {
    return null;
  }
}

export default Locater;

为此,为geolocate控件创建一个新变量,并将这个新创建的变量传递到您的map.addControl方法中。

在此之后,将geolocate._onClickGeolocate方法绑定到setTimeout()方法中的geolocate变量。

这将自动为您调用_onClickGeolocate方法。

import {Component } from "react";
import PropTypes from "prop-types";
import { accessToken } from "../../api/tokens/mapbox";
import mapboxgl from "mapbox-gl";

class Locator extends Component {
  static contextTypes = { map: PropTypes.object.isRequired };


  componentDidMount() {
    const { map } = this.context;

    const  geolocate  = 
      new mapboxgl.GeolocateControl({
        accessToken,
        positionOptions: {
          enableHighAccuracy: true
        },
        trackUserLocation: true
      })

    map.addControl(
      geolocate
    );
  setTimeout(geolocate._onClickGeolocate.bind(geolocate), 5)
  }


  render() {
    return null;
  }
}

export default Locator;

已经很晚了,但以下方法将起作用:

let geolocate = new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true,
      },
      trackUserLocation: true,
    });
    map.addControl(geolocate);

map.on("load", function () {
      geolocate.trigger();
    });

暂无
暂无

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

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