Ankit Sharma
Ankit Sharma

Reputation: 158

Saving current locations to database as soon as the user changes the position, Google Map API & Cordova by using Intel XDK

I am creating a transport app, I want to save the current position of the user as soon as they change the position to MySQL database and later I will fetch the result and plot the marker on the Map. here is my code for current location

    var watchid;
$( document ).on( "pagecreate", "#map-page", function() {
        var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434);  // Default to Hollywood, CA when no geolocation support
        if ( navigator.geolocation ) {
            function success(pos) {
                // Location found, show map with these coordinates
                drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
            }
            function fail(error) {
                drawMap(defaultLatLng);  // Failed to find location, show default map
            }
            // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
         watchid = navigator.geolocation.watchPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
        } else {
            drawMap(defaultLatLng);  // No geolocation support, show default map
        }
        function drawMap(latlng) {
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
            // Add an overlay to the map of current lat/lng
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title: "Greetings!"
            });
        }


    });

Upvotes: 1

Views: 1564

Answers (1)

IamKarim1992
IamKarim1992

Reputation: 646

Update every 1 ms seconds

var options = {enableHighAccuracy: true,timeout: 5000,maximumAge: 0,desiredAccuracy: 0, frequency: 1 };
            watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);

now in the onSuccess get the location

function onSuccess (position) {
    var newLocation = position.coords;
    if(newLocation .latitude === oldLocation.latitude && oldLocation.longitude === crd.longitude){
    //donot save in DB 
    } else{
    //save in db and draw it on map
     var myLatLng = new google.maps.LatLng( position.coords.latitude,position.coords.longitude  );
              drawmap(myLatLng );
            }

    }

swap around the value of newLocation and oldLocation , where your oldLocation initially is the current location and after every change in location flush out the value of newLocation and set your location as oldLocation. Hope it Helps.

Upvotes: 1

Related Questions