Skip to content

Instantly share code, notes, and snippets.

@cyanglee
Created January 3, 2014 12:15

Revisions

  1. cyanglee created this gist Jan 3, 2014.
    56 changes: 56 additions & 0 deletions browser_location.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    function render_result(queryText) {

    // Test if the broswer supports geolocation
    if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function(position) {
    // Get geolocation from the browser's location
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;

    var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=false";
    var result = null;
    var country_code = null;

    // clear out the old data before appending the new one
    $("#result").empty();

    $.getJSON(url)
    // Get the geolocation from google maps api and
    // pass the result to the next function after the request is done.
    .done(function(data) {
    // Extract the country from the google maps api.
    result = data.results[data.results.length-1].address_components[0].short_name;
    // Handle the situation when the country code is null.
    country_code = result === undefined ? default_country_code : result;
    // $.when(query_and_parse_api(queryText, country_code), fetch_google_map_html(queryText, country_code)).done(function(a1, a2){
    // });
    $.when(query_and_parse_api(queryText, country_code)).done(function(a1){
    });
    // $.when(fetch_google_map_html(queryText, country_code)).done(function(a1){
    // });
    });

    }), function(error) {
    var errorMessage;

    switch(error.code) {
    case 0:
    errorMessage = "unknown error";
    break;
    case 1:
    errorMessage = "permission denied";
    break;
    case 2:
    errorMessage = "position unavailable (error response from locaton provider)";
    break;
    case 3:
    errorMessage = "timed out";
    break;
    }
    console.log('Error occurred. Error code: ' + errorMessage);
    }
    } else {
    console.log('Geolocation is not supported for this Browser/OS version yet.');
    }
    }