Bilal Zafar
Bilal Zafar

Reputation: 457

Update User Locations after every 10 sec - get location form mysql

I am building an app which gets user data from mysql and show them on the map, From my android app, I update the table (lat,lon) every 10 seconds, Now I want to update their locations on google map (web app) without refreshing the map or page

Here is my code:

This function loads on page refresh

function initMap() {

    var mapOptions = {
    zoom: 11,
    center: {lat: 33.7167, lng: 73.0667},
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), 
 mapOptions);

    makeRequest('get_locations.php', function(data) {

    var data = JSON.parse(data.responseText);

        for (var i = 0; i < data.length; i++) {
            //display(data[i]);
            displayLocation(data[i]);
        }
    });
//window.setInterval(initMap, 15000);   
}

makeRequest Function

function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        callback(request);
    }
}
request.open("GET", url, true);
request.send();

}

get_location.php

<?php
include('connection.php');
$l= array();
$result = mysqli_query($con,"SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
$l[] = $row;
}
$j = json_encode($l, true);
echo $j;
//return $j;
?>

Display Location Function

function displayLocation(location) {

            var contentString ='<div class=\"chapter-bubble\">' 
+'<strong>Name: ' + location.username + '</strong>'+'<br/>'+'<strong>Phone: 
</strong>'+location.phone_number +'</strong>'+'<br/>'+'<strong><a 
href=\"sendsms.php?phone_number=' + location.phone_number + '&username=' + 
location.username +'\"> Send SMS</a> </strong>'+'<br/></div>' ;
            //window.alert(location.name);

            var position = new google.maps.LatLng(parseFloat(location.lat), 
parseFloat(location.lon));
            //window.alert(position);

            var image;
                if (location.is_safe=="0")
                {
                    image = new 
google.maps.MarkerImage('placer/not_safe.png', null, null, null, new 
google.maps.Size(40, 40));
                }
                else if (location.is_safe=="1")
                {
                    image = new 
google.maps.MarkerImage('placer/yes_safe.png', null, null, null, new 
google.maps.Size(40, 40));
                }

                //window.alert(image);



            var marker = new google.maps.Marker({
            position: position,
            map: map,
            icon: image,
            animation: google.maps.Animation.DROP,
            title: location.username
            });

            var infowindow = new google.maps.InfoWindow({
                content:contentString
            });
            google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
            });
}

What I have done is add this line window.setInterval(initMap, 5000); at the end of initMap function but it loads the map, I just want to change the locations only without refresing page or map. Any solution for this ?

Upvotes: 2

Views: 1032

Answers (1)

Joyson
Joyson

Reputation: 3040

You need to create an array and add the markers to the array. Before updating the new markers the markers need to be removed from the map. This can be done by using the clearMarkers method as given below

Declare this at the top of the js file

var markerArray = new Array();

Add the following method in the js file

function clearMarkers()
 {
     for(var j=0, len = markerArray.length; j<len; j++)
        {
         markerArray[j].setMap(null);     
        }
        markerArray = new Array();
 } 

Separate the code from initMap and create a new method called updateLocation

function updateLocation()
{
  makeRequest('get_locations.php', function(data) {

        clearMarkers();

        var data = JSON.parse(data.responseText);

            for (var i = 0; i < data.length; i++) {
                //display(data[i]);
                displayLocation(data[i]);
            }
        });
    window.setInterval(updateLocation, 15000); 
}

It will be called from initMap method

function initMap() {

    var mapOptions = {
    zoom: 11,
    center: {lat: 33.7167, lng: 73.0667},
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), 
 mapOptions);

  updateLocation();    
}

In the Display Location Function add the marker to the array after creating it:

var marker = new google.maps.Marker({
            position: position,
            map: map,
            icon: image,
            animation: google.maps.Animation.DROP,
            title: location.username
   });

 markerArray.push(marker);

Upvotes: 1

Related Questions