Plotting only the initial and final point on Google Maps using API

I am currently working on a tracking application that utilizes the Geolocation and Google Maps API. The app is set up to track the user's position using the watchPosition() function. As of now, a new blue icon is displayed every time a new longitude and latitude position is received. However, I would like the app to only plot the start position with a red marker, and then show the blue icon when it receives the latest coordinates instead of adding a new icon to the map for every new position.

Check out the CodePen Demo

Here is the code:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
</head>
<body>

<style type="text/css">
    html {
        height: 100%;
    }
    body {
        height: 100%;
        margin: 0;
        padding: 0;
    }

    #map_canvas {
        height: 100%;
        width: 100%;
    }
</style>

<div id="dvContent">

</div>

<div id="map_canvas">
    Hello
</div>
<!-- <input type="text" name="'adr" id="address" value="-41.2889, 174.7772" />
<input type="button" value="Start Watching" id="start">
<input type="button" value="Stop Watching" id="stop">
<input type="button" value="Delete Markers" id="delete"> -->


<script type="text/javascript">

    var watchID = null;
    var geo;
    var map;
    var startMarker = []; // Red Icon
    var endMarker = []; // Blue Icon
    var geo_options = {
        enableHighAccuracy: true, 
        maximumAge        : 10000000, 
        timeout           : 20000
    };
    var pathLineArray = new Array();
    var mypath;
    var geocoder;
    var mapMarkerRevCode;

    console.log(startMarker);



$(document).ready(function(){

    function getGeoLocation(){
        if (navigator.geolocation) {
            return navigator.geolocation;
        } else {
            return "undefined";
        }
    }

    function startWatching(){
        watchID = geo.watchPosition(show_coords, geo_error, geo_options);
        // watchID = geo.getCurrentPosition(show_coords, geo_error, geo_options);
    }

    function stopWatching(){
        if (watchID!=null) {
            geo.clearWatch(watchID);
        }
    }

    $('#start').click(startWatching);

    $('#stop').click(stopWatching);

    if(geo = getGeoLocation()){
        startWatching();
    } else {
        alert('Geolocation is not supported');
    }
});

function show_coords(position){

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    var latlng = new google.maps.LatLng(lat, lon);

    if (map) {

        // Makes it so that it doesnt have to reload the map everytime, it just pans to the new position
        map.panTo(latlng);

    } else {
        var myOptions = {
            zoom: 16,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

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

        var mypath = new google.maps.Polyline({
            path: pathLineArray,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            map: map

        });

        startMarker = new google.maps.Marker({
            position: latlng,
            map: map,

        });

    }
    // Push lat and long coords to this array
    pathLineArray.push(latlng);

    if (mypath) {
        mypath.setPath(pathLineArray);

    } else {
        mypath = new google.maps.Polyline({
            path: pathLineArray,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 4,
            map: map,

        });
    }

    endMarker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
    });


}


function geo_error(error){
    switch(error.code){
        case error.TIMEOUT:
        alert("geolocation timeout");
        break;
        case error.POSITION_UNAVAILABLE:
        alert("Gelocation position unavailable");
        break;
        case error.PERMISSION_DENIED:
        alert("Permission denied");
        break;
        default:
        alert('Unknown error');
    }
}

</script>


</body>
</html>

Answer №1

Instead of creating a new end marker each time, simply move the existing one.

if (endMarker && endMarker.setPosition) {
  endMarker.setPosition(latlng);
} else {
  endMarker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
  });
}

See it in action on this proof of concept fiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

Having trouble with conditional statements in jQuery when handling ajax responses?

I am currently working with the following code: $.ajax({ url: 'upload.php', //Server script to process data type: 'POST', xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if(myX ...

Angular confirmation page following successful HTTP POST request to Web API

First question here... I have been given the task of improving an Angular application, even though I am starting with zero experience in Angular. While I do have some background in JavaScript, I mostly work with Java (JSP's and yes, JavaScript). Despi ...

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...

Is there no "on" function available in the Node readline module?

I am currently working on building a Node.js application that reads a text file line by line using the 'readline' module and displays it in the console. var lineReader = require('readline'); lineReader.createInterface({ input: fs.cre ...

Dividing the array into distinct subarray groups

I am working with a JavaScript array that contains strings, like this: let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e&quo ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

Exploring the process of extracting/parsing HTML with Microdata

Hello, I am relatively new to the concept of Microdata. I currently have an HTML string that contains Microdata and I am interested in exploring the possibility of extracting the necessary information dynamically using Microdata with JavaScript or jQuery. ...

Having trouble pinpointing the issue with this particular if statement?

I am currently working on creating a form that compiles all entered data when the user fills out all fields. The form is connected to a PHP file and functions properly, but I encountered issues when implementing validation logic. The "Validation" section ...

Having trouble accessing the name property of a select dropdown in Material UI React

Currently, I am facing an issue with implementing a select dropdown. When handling the onChange method, I am encountering a situation where event.target.name is undefined. Specifically, when I choose the 1st option, I want to be able to access 'Englis ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

Adjusting the background color of the list item

I'm looking for a way to change the background color of the li tag when the user focuses on the input, similar to what can be seen at the bottom of this page here. After researching similar questions, it appears that achieving this effect in pure CSS ...

Trying out the ClientPortal in Next.JS with Jest Testing

I'm currently working with NextJS and I want to run tests on the ClientPortal component. My testing toolkit consists of Jest and React Testing Library. Below is a sample code snippet for the ClientPortal component: import { useEffect, useRef, useStat ...

Is there a neat method in React and Material UI for de-structuring the props that I am passing to useStyles?

When passing props to useStyles based on the Material docs, our code looks like this: const useStyles = makeStyles({ // style rule foo: props => ({ backgroundColor: props.backgroundColor, }), bar: { // CSS property color: props => ...

There seems to be an issue with accessing the requested page,

Having some trouble with routing in external files and getting a 'Cannot Get /' error. Can anyone help me figure out what I'm doing wrong? Here is my server.js file: const express = require('express'); const mongoose = require(&a ...

What is the best way to retrieve the value of a property within a JavaScript object?

I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...

Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of prom ...

Guide on utilizing Three.js OrbitControl with several objects

I managed to get the orbit control feature working, but I am facing an issue where controlling one object also ends up controlling all three objects on the page. Additionally, pan/zoom functionality does not seem to work at all with the OrthographicCamera. ...

Using JSON Object for Default Selection in an Angular Dropdown Menu

Here is some code I have that fills in a specific select item on a webpage: <select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br> I'm curious if there ...

Tips for switching out images depending on the time of day

Currently, I have a script that dynamically changes the background color of my webpage based on the time of day. However, I am facing issues trying to implement a similar functionality for replacing an image source. The current code is also time zone-based ...