4 Replies - 956 Views - Last Post: 02 July 2013 - 12:39 PM

#1 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

watchPosition() ft. Google Maps Glitch

Posted 02 July 2013 - 11:52 AM

Instruction
Please navigate to the web URL below using your mobile phone.

URL Link

Click 'Start' and wait for GPS to locate your position. Once located, you will be presented with a Google Map and Google Marker.

Problem
The GPS causes the Google Map and Google Marker to refresh consistently (almost every second), which causes the browser to crash.

Question
How can I resolve this so that ONLY the Google Marker is updated upon every refresh and NOT the Google Map?

Note
The source code can be viewed from the web URL.


Is This A Good Question/Topic? 0
  • +

Replies To: watchPosition() ft. Google Maps Glitch

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9179
  • View blog
  • Posts: 34,468
  • Joined: 12-June 08

Re: watchPosition() ft. Google Maps Glitch

Posted 02 July 2013 - 11:57 AM

Quote

Problem
The GPS causes the Google Map and Google Marker to refresh consistently (almost every second), which causes the browser to crash.

Perhaps show your relevant code.. I got limited time and I am not going to go try and sift through a website's "view source" window..


Quote

watchPosition() ft. Google Maps Glitch
...
Question
How can I resolve this so that ONLY the Google Marker is updated upon every refresh and NOT the Google Map?

Do you believe the problem is with google's setup or your code? The former may be better if you talk to them directly.
Was This Post Helpful? 0
  • +
  • -

#3 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

Re: watchPosition() ft. Google Maps Glitch

Posted 02 July 2013 - 12:02 PM

modi123_1,

Thanks for taking the time.

Please find my source code below.

// Javascript Document

window.onload = function () {
    document.getElementById('start').disabled = false;
    document.getElementById('stop').disabled = true;
};

start.addEventListener("click", function (event) {
    startTime = new Date();
});

var x = document.getElementById("info");

function getLocation() {
    if (navigator.geolocation) {
        document.getElementById('start').disabled = true;
        document.getElementById('stop').disabled = false;
        navigator.geolocation.watchPosition(showPosition, showError, clearWatch, {
            enableHighAccuracy: true,
            maximumAge: 60000,
            timeout: 30000
        });
    } else {
        x.innerHTML = "Your browser does not support the geolocation API.";
    }
}

var flightPathCoordinates = [];
var lat1, lng1, first_check;

function showPosition(position) {

    // Distance Calculator
    distance = 0;
    if (!first_check) {
        lat1 = position.coords.latitude;
        lng1 = position.coords.longitude;
        first_check = true;
    } else {
        var distanceFrom = function (points) {
            var lat1 = points.lat1;
            var radianLat1 = lat1 * (Math.PI / 180);
            var lng1 = points.lng1;
            var radianLng1 = lng1 * (Math.PI / 180);
            var lat2 = points.lat2;
            var radianLat2 = lat2 * (Math.PI / 180);
            var lng2 = points.lng2;
            var radianLng2 = lng2 * (Math.PI / 180);
            var earth_radius = 3959;
            var diffLat = (radianLat1 - radianLat2);
            var diffLng = (radianLng1 - radianLng2);
            var sinLat = Math.sin(diffLat / 2);
            var sinLng = Math.sin(diffLng / 2);
            var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);
            var distanc = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));
            return distanc.toFixed(0);
        };
        distance = distanceFrom({
            "lat1": lat1,
                "lng1": lng1,
                "lat2": position.coords.latitude,
                "lng2": position.coords.longitude
        });
    }

    x.innerHTML = "Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude +
        "<br>Accuracy: " + position.coords.accuracy +
        "<br>Altitude: " + position.coords.altitude +
        "<br>Altitude Accuracy: " + position.coords.altitudeAccuracy +
        "<br>Heading: " + position.coords.heading +
        "<br>Speed: " + position.coords.speed * 2.2369 + " (mph)" +
        "<br>Timestamp: " + new Date(position.timestamp).toLocaleString() +
        "<br>Distance Travelled: " + distance + " (miles)";

    lat = position.coords.latitude;
    lon = position.coords.longitude;
    timestamp = new Date(position.timestamp).toLocaleString();
    latlon = new google.maps.LatLng(lat, lon);
    mapholder = document.getElementById('mapholder');

    var myOptions = {
        center: latlon,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);

    // Custom Marker 1
    var image1 = '../images/logo_marker1.png';
    var marker1 = new google.maps.Marker({
        position: latlon,
        map: map,
        icon: image1,
        title: "You are here!"
    });

    // Bicycle Store
    var request2 = {
        location: (latlon),
        radius: '500',
        types: ['bicycle_store']
    };
    infowindow2 = new google.maps.InfoWindow();
    var service2 = new google.maps.places.PlacesService(map);
    service2.nearbySearch(request2, callback2);

    function callback2(results2, status2) {
        if (status2 == google.maps.places.PlacesServiceStatus.OK) {
            for (var i2 = 0; i2 < results2.length; i2++) {
                var place2 = results2[i2];
                createMarker2(results2[i2]);
            }
        }
    }

    function createMarker2(place) {
        var placeLoc2 = place.geometry.location;

        // Custom Marker 2
        var image2 = '../images/logo_marker2.png';
        var marker2 = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            icon: image2,
            title: "Bicycle Store"
        });
        google.maps.event.addListener(marker2, 'click', function () {
            infowindow2.setContent(place.name);
            infowindow2.open(map, this);
        });
    }

    // Cafe
    var request3 = {
        location: (latlon),
        radius: '500',
        types: ['cafe']
    };
    infowindow3 = new google.maps.InfoWindow();
    var service3 = new google.maps.places.PlacesService(map);
    service3.nearbySearch(request3, callback3);

    function callback3(results3, status3) {
        if (status3 == google.maps.places.PlacesServiceStatus.OK) {
            for (var i3 = 0; i3 < results3.length; i3++) {
                var place3 = results3[i3];
                createMarker3(results3[i3]);
            }
        }
    }

    function createMarker3(place) {
        var placeLoc3 = place.geometry.location;

        //Custom Marker 3
        var image3 = '../images/logo_marker3.png';
        var marker3 = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            icon: image3,
            title: "Cafe"
        });
        google.maps.event.addListener(marker3, 'click', function () {
            infowindow3.setContent(place.name);
            infowindow3.open(map, this);
        });
    }

    //Bicycle Layer
    var bikeLayer = new google.maps.BicyclingLayer();
    bikeLayer.setMap(map);

    //Panoramio Layer
    var panoramioLayer = new google.maps.panoramio.PanoramioLayer();

    panoramioLayer.setUserId("7467601");
    panoramioLayer.setMap(map);
    google.maps.event.addListener(panoramioLayer, 'click', function (event) {
        var attribution = document.createTextNode(event.featureDetails.title + ": " + event.featureDetails.author);
        var br = document.createElement("br");
        var link = document.createElement("a");
        link.setAttribute("href", event.featureDetails.url);
        link.appendChild(attribution);
    });

    //Polyline Layer
    flightPathCoordinates.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    var flightPath = new google.maps.Polyline({
        path: flightPathCoordinates,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    flightPath.setMap(map);
}

function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation.";
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable.";
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out.";
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred.";
            break;
    }
}

// History Information Array
var historyInfo = localStorage.getItem("history");
if (!historyInfo) {
    historyInfo = [];
} else {
    historyInfo = JSON.parse(historyInfo);
}

function clearWatch(position) {
    document.getElementById('start').disabled = false;
    document.getElementById('stop').disabled = true;
    navigator.geolocation.clearWatch(position);
    endTime = new Date();

    // Duration Calculator
    var difference = endTime - startTime;
    var diffSeconds = difference / 1000;
    var HH = Math.floor(diffSeconds / 3600);
    var MM = (Math.floor(diffSeconds % 3600) / 60).toFixed();
    var duration = ((HH < 10) ? ("0" + HH) : HH) + ":" + ((MM < 10) ? ("0" + MM) : MM);

    historyInfo.push("<li>You travelled " + distance + " mile(s) in " + duration + " on " + timestamp + "." + "</li>");

    localStorage.setItem("history", JSON.stringify(historyInfo));
}

// localStorage
if (typeof (Storage) !== "undefined") {
    if (localStorage.getItem("history") === null) {
        document.getElementById("history").innerHTML = "There are currently no records to display.";
    } else {
        document.getElementById('clear').disabled = false;
        for (var i = 0; i < historyInfo.length; i++) {
            document.getElementById("history").innerHTML += historyInfo[i];
        }
    }
} else {
    document.getElementById("history").innerHTML = "Your browser does not support the localStorage API.";
}


I'm not sure if this a fault of mine or Google's.
Was This Post Helpful? 0
  • +
  • -

#4 laytonsdad  Icon User is offline

  • Cheese and Sprinkles
  • member icon

Reputation: 439
  • View blog
  • Posts: 1,864
  • Joined: 30-April 10

Re: watchPosition() ft. Google Maps Glitch

Posted 02 July 2013 - 12:12 PM

function loadMarker() {
  new google.maps.Marker({position: latlng, map: map, title:"your title"});
}
setTimeout(function() { loadMarker(); },5000);


Something like this would work

You will need to get refresh the marker sepreate.
Was This Post Helpful? 0
  • +
  • -

#5 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

Re: watchPosition() ft. Google Maps Glitch

Posted 02 July 2013 - 12:39 PM

laytonsdad,

Thanks for your time.

I used your solution. However, this still causes the Google Map and Google Marker to refresh. I just want the Google Marker to be updated with every refresh, NOT the Google Map.

I have attempted cutting and pasting my map code within a different function (as I think this is the solution) but it did not work as intended.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1