Search code examples
javascriptgoogle-chromegoogle-maps-api-3geolocationgoogle-chrome-devtools

Google Chrome: Override geolocation via console


So a little background for my question; I am writing a simple driving instructions web application using Google Maps directions API which provides me with a LatLng path along with text instructions.

In order to test this application (without driving around in a car) I need to simulate a geolocation-path. Google Chrome supports overriding geolocation data via the sensors developer settings, which works fine with one coordinate at the time.

So my question is - is it possible to set the browsers navigator.geolocation data via the console (i.e. javascript api) instead manually updating the value in the sensors settings menu?

I know that in this case I could just use another input source than the browser geolocation data and use a static array of LatLng's, or override the browsers navigator.geolocation.getCurrentPosition, but I figured that it would be more sophisticated to override the sensors instead.

Thanks in advance.


Solution

  • One way is to override the function navigator.geolocation.getCurrentPosition with your own custom function. Inside the custom function you can customize the value of latitude & longitude.

    var customPosition = {};
    customPosition.coords = {};
    customPosition.coords.latitude = 41.89;
    customPosition.coords.longitude = 2.89;
    
    navigator.geolocation.getCurrentPosition = function(success, error){
        success(customPosition);
    
    };
    
    function success(position) {
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
    
        console.log("latitude: " + latitude);
        console.log("longitude: " + longitude);
      }