admin管理员组

文章数量:1026989

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
  });
});

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
  });
});

本文标签: