HTML 5 Geo Location Prompt in Chrome

AGoodDisplayName picture AGoodDisplayName · Mar 24, 2011 · Viewed 99.8k times · Source

Just starting to get into HTML 5 and an testing out geo location...liking it so far. I am hitting a bit of a speed bump though...when I try to get my geo location, chrome automatically blocks the page from getting my location. This does not happen at other sites such as the site below:

http://html5demos.com/geo

The scripts I'm using:

<script type="text/javascript" JavaScript" SRC="geo.js"></script>   
<script type="text/javascript" JavaScript" SRC="Utility.js"></script> 
<script type="text/javascript" JavaScript" SRC="jquery.js"></script> 
<script type="text/javascript" JavaScript" SRC="modernizr.js"></script>  

function get_location() {

        if (geo_position_js.init()) {
            geo_position_js.getCurrentPosition(show_map, handle_error);
        }

    }
    function show_map(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        alert("lat:" + latitude + " long:" + longitude);


    }
    function handle_error(err) {
        alert(err.code);
        if (err.code == 1) {
            // user said no!
        }
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_map, handle_error);
    } else {
        error('not supported');
    }

I am testing this out from a local directory on my machine, so there isn't really a "domain" like "http://whatever.com/mytestpage.html". Is this why I am not getting prompted? If so, is it possible to force the browswer to request permission to get the user's geo location and is it possible in my scenario?

Answer

robertc picture robertc · Mar 25, 2011

There's some sort of security restriction in place in Chrome for using geolocation from a file:/// URI, though unfortunately it doesn't seem to record any errors to indicate that. It will work from a local web server. If you have python installed try opening a command prompt in the directory where your test files are and issuing the command:

python -m SimpleHTTPServer

It should start up a web server on port 8000 (might be something else, but it'll tell you in the console what port it's listening on), then browse to http://localhost:8000/mytestpage.html

If you don't have python there are equivalent modules in Ruby, or Visual Web Developer Express comes with a built in local web server.