I am using the following code to add the GeolocateControl
to my react-mapbox-gl map in react.
I need to automatically call the method _onClickGeolocate
method using setTimeout()
to request the user location automatically upon loading the page.
How would I be able to achieve this ?
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;
To do this create a new variable for the geolocate
control, and pass this newly created variable into your map.addControl
method.
Following this bind the geolocate._onClickGeolocate
method to the geolocate
variable within the setTimeout()
method.
This will automatically call the _onClickGeolocate
method for you.
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;
it is very late, but the following will work:
let geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
trackUserLocation: true,
});
map.addControl(geolocate);
map.on("load", function () {
geolocate.trigger();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.