High accuracy geolocation Html5
Asked Answered
F

3

26

I am tring to locate a device using the embedded GPS (like whats app share location). I've read that it is possible with enableHighAccuracy: true.

How can I set enableHighAccuracy: true in this code? I tried in different positions but it doesn't work.

<script type="text/javascript">
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var accuracy = position.coords.accuracy;
            var coords = new google.maps.LatLng(latitude, longitude);
            var mapOptions = {
                zoom: 15,
                center: coords,
                mapTypeControl: true,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.SMALL
                },
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var capa = document.getElementById("capa");
            capa.innerHTML = "latitude: " + latitude + ", longitude: " + ", accuracy: " + accuracy;  

            map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
            var marker = new google.maps.Marker({
                position: coords,
                map: map,
                title: "ok"
            });
        });

    } else {
        alert("Geolocation API is not supported in your browser.");
    }

</script>
Fibrosis answered 24/4, 2013 at 20:59 Comment(0)
P
39

You need a PositionOptions object, in which you set the high accuracy flag following the API.

I am quoting from here: http://diveintohtml5.info/geolocation.html

The getCurrentPosition() function has an optional third argument, a PositionOptions object. There are three properties you can set in a PositionOptions object. All the properties are optional. You can set any or all or none of them.

POSITIONOPTIONS OBJECT

Property            Type        Default         Notes
--------------------------------------------------------------
enableHighAccuracy  Boolean     false           true might be slower
timeout             long        (no default)    in milliseconds
maximumAge          long        0               in milliseconds

So, it should work like this:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var accuracy = position.coords.accuracy;
        var coords = new google.maps.LatLng(latitude, longitude);
        var mapOptions = {
            zoom: 15,
            center: coords,
            mapTypeControl: true,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.SMALL
            },
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var capa = document.getElementById("capa");
        capa.innerHTML = "latitude: " + latitude + ", longitude: " + ", accuracy: " + accuracy;

        map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
        var marker = new google.maps.Marker({
            position: coords,
            map: map,
            title: "ok"
        });

    },
    function error(msg) {alert('Please enable your GPS position feature.');},
    {maximumAge:10000, timeout:5000, enableHighAccuracy: true});
} else {
    alert("Geolocation API is not supported in your browser.");
}

Noticed I added the following 2 parameters to getCurrentPosition call:

  1. function error(msg){alert('Please enable your GPS position future.');}

    This function is called when GPS could not be retrieved or the timeout has been triggered.

  2. {maximumAge:10000, timeout:5000, enableHighAccuracy: true});

    These are the options. We don't want gps data that is older than 10 seconds (maximumAge:10000). We don't want to wait longer than 5 seconds for a response (timeout:5000) and we want to enable high accuracy (enableHighAccuracy: true).

Also see: Geolocation HTML5 enableHighAccuracy True , False or Best Option?

Per answered 24/4, 2013 at 21:33 Comment(2)
Thanks!! However, I can't get less than 65 meters accuracy :(Fibrosis
@meework You have set the enableHighAccuracy false instead of setting it true.Coldshoulder
I
9

Here's a simple example of enableHighAccuracy: true taken from the Mozilla Developer Network.

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);
Iy answered 24/10, 2018 at 14:34 Comment(0)
M
0
if(navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(position => {
       do_whatever_you_want
},
error => console.log(error),
{enableHighAccuracy: true}
)
}

EXPLANATION: First of all, i am checking if the browser supports the geolocation using the if conditional on the top and wrapping whole code in it. If it exists then i try to get getCurrentPosition which returhs an object containing some info like the coordinates.I call that object position. So if you want to get the lat and lng;

var lt = position.coords.latitude;
var ln = position.coords.longitude;

GetCurrentPosition takes some more arguments also. As first one was if it ran successfully(then i tried to get the returned object). The second one is the error. I console logged the error here. Third one is the extra options. One of those options is enableHighAccuracy. If set to true it will try to get the most accurate location from the user.

Martyrdom answered 17/12, 2020 at 12:33 Comment(3)
please some explain of your answerCongregation
didnt work for me. Shows the same presizenees as if i use it w/o enableHighAccuracy: true expressionGrapeshot
Can you please share the details about your device which you are using.Martyrdom

© 2022 - 2024 — McMap. All rights reserved.