mkyong
mkyong

Reputation: 12947

Updating Google Map Marker

I'm trying to make a Google map that updates a marker as a user's location is updated. I have most of it done, but I'm having one small issue. I want one marker that shows the starting point, which I have working, but the second point should keep moving, and it should allow multiple users to be tracked at once.

I can get this to work for one user (sending GPS coordinates from Android app). It will set the start marker, and as their location changes the marker will move to reflect that. My problems occur when I start tracking a second user. The current position marker for the first user becomes the starting location for the second user. It 'jumps' from the first path to the other (see picture). I know this is partly due to the declaration of the 'marker1' variable at the top, but I've tried many things with no luck. I need to be able to create as many as I need for n number of users so I can't declare a bunch of variables for each one. enter image description here

You can see in the picture what is happening. This is the moment when a new user triggers the tracking function in the app. Before this second user activates the tracking function, the marker for the first user was moving properly.

    function initialize() {
    var myLatlng = new google.maps.LatLng(39, -86);
    var myOptions = {
        zoom: 6,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    }       
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    var loc = {};
    var mark = {};
    var markers = {};
    var marker1;

    $(function () {
        $(document).ready(function(){
            setInterval(function(){
                $.ajax({                                      
                    url: 'api.php',                  //the script to call to get data          
                    //data: "",                       
                    dataType: 'json',                //data format      
                    success: function(data){          //on recieve of reply                          


                        var user_id = data[0];
                        var lati = data[1];              //get id
                        var longi = data[2];           //get name

                        var myLatlngt = new google.maps.LatLng(lati, longi);

                        if (typeof loc[user_id] === 'undefined') {
                            loc[user_id] = [];
                            }

                        //if (typeof markers[user_id] === 'undefined') {
                            //markers[user_id] = [];
                            //}

                        if (typeof mark[user_id] === 'undefined') {
                            mark[user_id] = myLatlngt;
                            }

                        loc[user_id].push(myLatlngt);
                        //markers[user_id].push(myLatlngt);

                        var x;
                        for (x in loc) {
                            var polyline = new google.maps.Polyline({
                                map: map,
                                path: loc[x],
                                strokeColor: "#FF0000",
                                strokeOpacity: 1.0,
                                strokeWeight: 2
                                });
                            polyline.setMap(map);

                            ///location variables
                            var start_loc = loc[user_id];
                            var start_marker = start_loc[0]; //start location of given user
                            var current_loc = start_loc[start_loc.length -1]; //last known location of given user

                            //set the start marker
                            var marker = new google.maps.Marker({
                                position: start_marker,
                                title: user_id
                            });
                            marker.setMap(map); 

                            //update the current location marker
                            if (marker1 != null) {
                                marker1.setPosition(current_loc);
                            }
                            else {
                                marker1 = new google.maps.Marker({
                                    position: current_loc,
                                    map: map
                                });

                            }                   
                        }
                            //console.log('location :::', x);
                            console.log('Marker: ', mark);
                    } 
                });
            }, 1000);
        });
    });
}

Upvotes: 0

Views: 1249

Answers (2)

ThinkingStiff
ThinkingStiff

Reputation: 65341

It's not totally clear what the issue is, but have you tried using .panTo()? It scrolls smoothly to a new location. Call it after your .setPosition().

if (marker1 != null) {
    marker1.setPosition(current_loc);
    map.panTo( current_loc );
}

Upvotes: 0

Johan
Johan

Reputation: 318

Considering that I don't really know javascript I may be totaly wrong here, but I am assuming that the anonymous function sent as argument to setInterval is called multiple times (?).

If that is the case, I would expect marker1 to be reused since it is declared outside of the function, I.e, it is the same marker1 used for every function call in this part of the code

//update the current location marker
if (marker1 != null) {
    marker1.setPosition(current_loc);
}

I guess you could use the same method for the marker1 as you did for the loc, having it as an array indexed by the user ID. (perhaps calling it currentLocationMarker would be a better name too)

Another way would be to have the marker1 only existing within the function, but that may cause all the previous current location markers for a user to be visible. Not sure about that, I do not get the full picture of this system you are building.

Upvotes: 1

Related Questions