Geolocation

by dcardoso

HTML

<p id="geolocation">Finding geolocation...</p>
<div id="map_canvas" style="width:500px; height:500px"></div>

JavaScript

$(function() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
});


// onSuccess Geolocation
//
function onSuccess(position) {
    var element = document.getElementById('geolocation');
    element.innerHTML = 'Latitude: '           + position.coords.latitude              + '<br />' +
                        'Longitude: '          + position.coords.longitude             + '<br />' +
                        'Altitude: '           + position.coords.altitude              + '<br />' +
                        'Accuracy: '           + position.coords.accuracy              + '<br />' +
                        'Altitude Accuracy: '  + position.coords.altitudeAccuracy      + '<br />' +
                        'Heading: '            + position.coords.heading               + '<br />' +
                        'Speed: '              + position.coords.speed                 + '<br />' +
                        'Timestamp: '          + new Date(position.timestamp)          + '<br />';
                        
    currentPosition = position;
                        
    loadGoogleMapsAPI();
}

// onError Callback receives a PositionError object
//
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}



var map = false,
    defaultLatlng = {},
    currentPosition = {};

function loadGoogleMapsAPI() {
    if(!map) {
        var script = document.createElement("script");

        script.type = "text/javascript";
        script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
        document.body.appendChild(script);
    } else {
        initialize();
    }
}


function initialize() {

    // Set the default coordinates to center the map
    defaultLatlng = new google.maps.LatLng(currentPosition.coords.latitude, currentPosition.coords.longitude);

    // Map options
    var myOptions = {
        zoom : 8,
        center : defaultLatlng,
        mapTypeId :...