Jerry Jones
Jerry Jones

Reputation: 796

Move Google Map marker dynamically using javascript

I have a div where I show user's current location. What I need is, when user moves, the marker should move dynamically using users curent location which is fetched through ajax and from my database. The map is initiated through mouse onclick event since there are multiple users. My entire code block looks like this: HTML Part:

<div id="map" class="mapBlock" style="width: 100%; height: 400px;"></div>
<button class="btn btn-info btn-sm mr-2 trackUser" data-toggle="modal" data-target="#trackUser"  data-did="<?php echo trim($user['did']);?>" onclick="getDid(this.getAttribute('data-did'));">Track User</button>

Javascript Part:

    var position = [10.1563183,76.3882613];
    var did = 1;
    var cord = [10.1563183,76.3882613];

    function getDid(x){
        did = x;
        initialize();
        //Load google map
        google.maps.event.addDomListener(window, 'load', initialize);
    }

    function initialize() { 
        var latlng = new google.maps.LatLng(position[0], position[1]);
        var myOptions = {
            zoom: 18,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map"), myOptions);

        marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: "Latitude:"+position[0]+" | Longitude:"+position[1]
        });
        //auto refresh - update marker to current - position center
        var refreshId = setInterval("getLatLong(did)", 10000);
    }
    //get new lat/long
    function getLatLong(id) {
        var data = new FormData();
        data.append('did', id);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'users/get_user_location', true);
        xhr.onload = function () {
            if(xhr.status !== 200){
                return;
            }
            cord = this.responseText;
        };

        xhr.send(data);

        transition(cord);
    }

    var numDeltas = 100;
    var delay = 10; //milliseconds
    var i = 0;
    var deltaLat;
    var deltaLng;

    function transition(result){
        i = 0;
        deltaLat = (result[0] - position[0])/numDeltas;
        deltaLng = (result[1] - position[1])/numDeltas;
        moveMarker();
    }

    function moveMarker(){
        position[0] += deltaLat;
        position[1] += deltaLng;
        var latlng = new google.maps.LatLng(position[0], position[1]);
        marker.setTitle("Latitude:"+position[0]+" | Longitude:"+position[1]);
        marker.setPosition(latlng);

        if(i!=numDeltas){
            i++;
            setTimeout(moveMarker, delay);
        }
    }

Everything is working fine but when the setinterval function is fired, the marker get disappeared.

Upvotes: 0

Views: 2950

Answers (1)

ascsoftw
ascsoftw

Reputation: 3476

Your moveMarker() method is working fine. Your marker does not disappears. It just moves out of the view.

You could fix that in 2 ways:

  1. Decrease the zoom Level. It is currently set to 18. You could set it to 12 or something.
    var myOptions = {
        zoom: 12, //Decrease your Zoom Level.
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
  1. Other way is you could move the center of your map as you are moving your Marker. You should do it just before you are using the setPosition of the Marker as below
        map.setCenter(latlng); //Here center the map.
        marker.setPosition(latlng);

I am not sure why you are calling moveMarker from inside the moveMarker using setTimeout. This will recursively call your method but it would not make any difference to the map co-ordinates. You are already calling getLatLong after every 10 seconds and it should be enough.

Upvotes: 1

Related Questions