最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

geolocation - How to locate a user without clicking on the control button? (MapBox API, JavaScript) - Stack Overflow

programmeradmin2浏览0评论

I'm trying to locate the user when the website is fully loaded. I'm using the newest MapBox API (JavaScript)

Is it possible to do that without requiring the user to click on the top right button on the map?

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [0,0],
    zoom: 15 // starting zoom
});
// Add geolocate control to the map.
map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: {
       enableHighAccuracy: true
    },
    trackUserLocation: true
}));

I'm trying to locate the user when the website is fully loaded. I'm using the newest MapBox API (JavaScript)

Is it possible to do that without requiring the user to click on the top right button on the map?

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [0,0],
    zoom: 15 // starting zoom
});
// Add geolocate control to the map.
map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: {
       enableHighAccuracy: true
    },
    trackUserLocation: true
}));
Share Improve this question asked May 23, 2019 at 10:19 JustinJustin 311 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Yes, you have to use trigger() to activate the tracking in a programmed way.

// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
    enableHighAccuracy: true
  },
  trackUserLocation: true
});

// Add the control to the map.
map.addControl(geolocate);
map.on('load', function() {
  geolocate.trigger(); //<- Automatically activates geolocation
});

see https://docs.mapbox./mapbox-gl-js/api/markers/#geolocatecontrol-instance-members

try with this example, it's work for me

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://cdnjs.cloudflare./ajax/libs/mapbox-gl/0.53.1/mapbox-gl.js'></script>
    <link href='https://cdnjs.cloudflare./ajax/libs/mapbox-gl/0.53.1/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
    <script  >
    var get_location = function() {
    var geolocation = null;
    var c_pos = null;

    if (window.navigator && window.navigator.geolocation) {
        geolocation = window.navigator.geolocation;

        var positionOptions = {
            enableHighAccuracy: true,
            timeout: 10 * 1000, // 10 seconds
            maximumAge: 30 * 1000 // 30 seconds
        };

        function success(position) {
            console.log(position);
            c_pos = position.coords;
            mapboxgl.accessToken = 'token';  /////////////////  put your token here 
            if (!mapboxgl.supported()) {
                alert('Your browser does not support Mapbox GL');
            } else {
                var map = new mapboxgl.Map({
                    container: 'map', // container id
                    style: 'mapbox://styles/mapbox/streets-v11',  
                    center: [c_pos.longitude, c_pos.latitude], 
                    zoom: 12 // starting zoom
                });
            }
        }

        function error(positionError) {
            console.log(positionError.message);
        }

        if (geolocation) {
            geolocation.getCurrentPosition(success, error, positionOptions);
        }

    } else {
        alert("Getting Geolocation is prevented on your browser");
    }

    return c_pos;
}
    </script>
</head>
<body>

<div id='map'></div>
<script>
    var current_pos = get_location();
</script>

</body>
</html>

try with this

navigator.geolocation.getCurrentPosition(position => {
  const userCoordinates = [position.coords.longitude, position.coords.latitude];
  map.addSource("user-coordinates", {
    type: "geojson",
    data: {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: userCoordinates
      }
    }
  });
  map.addLayer({
    id: "user-coordinates",
    source: "user-coordinates",
    type: "circle"
  });
  map.flyTo({
    center: userCoordinates,
    zoom: 14
  });
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论