0

Good day! I have a native app using cordova (html and javascript). I need help with moving the marker on the map in real time manner as the user changes its position or the coordinates change.

Here's the full source code of mapping.js

var mbAttr =
    'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
    '© <a href="https://www.mapbox.com/">Mapbox</a>',
  mbUrl =
    "https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw";

var redIcon = new L.Icon({
  iconUrl:
    "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

var violetIcon = new L.Icon({
  iconUrl:
    "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-violet.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [35, 51],
  iconAnchor: [17, 51],
  popupAnchor: [1, -34],
  shadowSize: [51, 51]
});

var streets = L.tileLayer(mbUrl, { id: "mapbox.streets", attribution: mbAttr });

var mymap;
var locationHistory = [];
var watch;

function f1(a, b) {
  lat = a;
  lon = b;

  mymap = L.map("mapid", {
    center: [14.54965, 121.00737],
    zoom: 16,
    layers: [streets]
  });

  L.marker([14.4311, 120.9682], { icon: violetIcon })
    .addTo(mymap)
    .bindPopup("New Bacoor City Hall");

  L.marker([a, b], { icon: redIcon })
    .addTo(mymap)
    .bindPopup("You are here.")
    .openPopup()
    .update();
}


function getLocation() {
  navigator.geolocation.getCurrentPosition(showPosition, showError);
}

function showPosition(position) {
  f1(position.coords.latitude, position.coords.longitude);
}

function showHistory() {
  var el = document.getElementById("historyWrapper");
  if (el.style.display === "none") {
    el.style.display = "block";
  } else {
    el.style.display = "none";
  }
}

function startWatching() {
  var toastHTML = "Tracking started...";
  M.toast({html: toastHTML, displayLength: 3000});
  watch = navigator.geolocation.watchPosition(onSuccess, onError, {
    maximumAge: 10000,
    timeout: 5000,
    enableHighAccuracy: true
  });
  var el = document.getElementById("historyWrapper");
  el.style.display = "none";
}

function stopWatching() {
  if (confirm("Do you want to stop tracking?")) {
    var toastHTML = "Tracking Stopped.";
    M.toast({html: toastHTML, displayLength: 3000});
    navigator.geolocation.clearWatch(watch);
    var el = document.getElementById("locationHistory");
    locationHistory.forEach(function(location) {
      el.innerHTML =
        "<li>Latitude: " +
        location.coords.latitude +
        "<br />" +
        "Longitude: " +
        location.coords.longitude +
        "<br />" +
        "<strong>Date: " +
        new Date().toLocaleString() +
        "</strong><hr /></li>" +
        el.innerHTML;
    });
    document.getElementById("historyWrapper").style.display = "block";

    document.getElementById("geolocation").innerHTML = "";
  }
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      var toastHTML = "User denied the request for geolocation.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
    case error.POSITION_UNAVAILABLE:
      var toastHTML = "Location information is unavailable.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
    case error.TIMEOUT:
      var toastHTML = "The request to get user location timed out.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
    case error.UNKNOWN_ERROR:
      var toastHTML = "An unknown error occurred.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
  }
  window.close();
}

function onSuccess(position) {
  locationHistory.push(position);
  var element = document.getElementById("geolocation");
  element.innerHTML = "";
  element.innerHTML =
    "Latitude: " +
    position.coords.latitude +
    "<br />" +
    "Longitude: " +
    position.coords.longitude +
    "<br />" +
    "<hr />" +
    element.innerHTML;
}

function onError(error) {
  var toastHTML = "code: " + error.code + "\n" + "message: " + error.message + "\n";
  M.toast({html: toastHTML, displayLength: 3000});
}

getLocation();

So, I have 3 buttons on my html file that calls the 3 functions from the js file - startWatching() , stopWatching() and showHistory()

function startWatching() will watch coordinates as the user moves or change location. function stopWatching() will stop watching or getting coordinates. function showHistory() will display the list of coordinates watched.

var redIcon is the marker for the location of the user after getLocation() var violetIcon is the marker for the defined location

The function f1(a, b) will display 2 markers on the map - one marker is for a defined location and the other marker is the location of the user when function getLocation() takes place.

Now, I need to move the marker of user's location when the user changes its position or when a new coordinates is generated on the map. I hope someone will help me on this. Thanks in advance`

1 Answer 1

2

You need to access your user marker outside of the f1 function. You could do this by assigning the marker to a globally defined variable.

Define your marker variable in the global scope.

var userMarker = null;

In your f1 function assign the created marker to the userMarker variable.

function f1(a, b) {
  ...
  userMarker = L.marker([a, b], { icon: redIcon })
    .addTo(mymap)
    .bindPopup("You are here.")
    .openPopup()
    .update();
}

Now you can use the userMarker marker instance in your onSuccess function when the position of the user has been updated. Use the setLatLng() method to update the position of the marker with new coordinates.

function onSuccess(position) {
  // Destructure assignment to get the lat and long from the position object.
  let { latitude, longitude } = position.coords;
  if (userMarker !== null) {
    userMarker.setLatLng([latitude, longitude]);
  }
}
1
  • hi @emiel your answer really worked for me! Thanks a lot for your help!! I'd like to add on the answer to remove the 'null' on var userMarker. Thanks again! Commented Mar 29, 2020 at 13:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.