Search code examples
mapboxmapbox-gl-jsmapbox-glmapbox-marker

Mapbox showing location from my Internet service provider(ISP) IP address


Mapbox showing the location from my Internet service provider(ISP) IP address and not from the IP address of my desktop connected to my home network over WIFI, however, it does track the correct position of my mobile device connected to the same home network.

How would I go about fixing this issue?

Index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js'></script>
    <script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.js"></script>
    <link href='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css' rel='stylesheet'/>
    <link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.css" type="text/css"/>
    <title>Mapbox Test</title>
</head>
<body>
    <div id='map' ></div> 
    <script src="js/basic_map.js" defer></script>
</body>
</html>

basic_map.js:

// mapbox access Key
mapboxgl.accessToken = ACCESS_TOKEN;

// Get My Current Location
navigator.geolocation.getCurrentPosition(successLocation, errorLocation, { enableHighAccuracy: true});

function successLocation(position)
{
    center = [position.coords.longitude, position.coords.latitude];
    zoom = 15;
    setupMap(center, zoom);
}

function errorLocation()
{
    // Fallback: Cape Town
    center = [18.4241, -33.9249];
    zoom = 10;
    setupMap(center, zoom);
}

function setupMap(center,zoom)
{
    const map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v11',
        center: center,
        zoom: zoom
        });



    map.on('load', function() 
    {
        // Add Navigation Buttons
        const nav = new mapboxgl.NavigationControl();
        map.addControl(nav, 'top-right');

        //  Add Marker
        const  marker = new mapboxgl.Marker()
        .setLngLat(center)
        .addTo(map);
    });
}

Solution

  • That's just intrinsic to how geolocation works. A mobile device has a GPS in it, plus 3G/4G, wi-fi etc - lots of ways to know where it is. A desktop computer doesn't have that information: only its IP address. So the geolocation service is making its best guess, and winding up at your ISP.