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

Maximizing performance: optimizing Javascript usage in .net Web Application

After completing a web application using C#, ASP, and some javascript, my main page is cluttered with a mix of javascript/jQuery at the bottom. I have several ajax calls to web methods in this mess. Is there a way to organize this javascript into multipl ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Looking to personalize the appearance of an iframe using CSS styling?

I am working with an iframe that generates a form, and I would like to customize the CSS of this form. How can I go about editing the CSS? <div class="quiz-container" style="text-align: center;" data-quiz="#######" data-pr ...

I am encountering an issue with the material ui dropdown component in my react native app where I am receiving a TypeError stating that it cannot read the property 'style' of undefined. This error is likely caused

Upon installation of Material UI and importing The Dropdown component, I encountered the error TypeError: Cannot read property 'style' of undefined, js engine: hermes. This is my code import React, { useEffect, useState } from "react"; import { ...

Troubleshooting problems with a JavaScript game that involves guessing numbers

I have been given a challenging Javascript assignment that involves using loops to create a counting betting game. The concept is simple: the User inputs a number, and the computer randomly selects a number between 1 and 10. The User can then bet up to 10 ...

The pre tag does not have any effect when added after the onload event

I have been experimenting with a jQuery plugin for drawing arrows, detailed in this article. When using the plugin, this code is transformed: <pre class="arrows-and-boxes"> (Src) > (Target) </pre> into this format: Src --> Target The is ...

Only Chrome causing my JavaScript execution to freeze due to Ajax

When using Ajax, it is supposed to be asynchronous, but for some reason, it seems like it's either stopping or pausing my JavaScript execution and only resuming once the response is received. Here is an example of HTML value: <input value="foo" d ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Utilize ngModel in conjunction with the contenteditable attribute

I am trying to bind a model with a tag that has contenteditable=true However, it seems like ngModel only functions with input, textarea or select elements: https://docs.angularjs.org/api/ng/directive/ngModel This is why the following code does not work ...

Ensuring the accuracy of a single field within a form containing multiple fields is made possible through the utilization of

I am facing an issue with my emailValidation method. Even though I want it to run when this.$refs.editUserForm.validate('email') returns true, it always seems to return false, especially when a valid email like <a href="/cdn-cgi/l/email-protec ...

What is the best way to create titles with a background?

My goal is to have a title overlay an image with specific width and the text displayed in blocks. To better illustrate, here's an example: I prefer to achieve this effect using CSS; however, I am open to utilizing Javascript if needed. ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

JQuery / Javascript - Mouse Position Erroneously Detected

I'm currently working on developing a drawing application where users can freely draw by moving their mouse over a canvas. My goal is to create a pixel at the precise location where the user drags their mouse. However, I've encountered an issue ...

Identify the significance within an array and employ the filter function to conceal the selected elements

I'm in the process of filtering a list of results. To do this, I have set up a ul list to display the results and checkboxes for selecting filter options. Each item in the ul list has associated data attributes. When a checkbox with value="4711" is c ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Determining the width of a window using JavaScript

My website is experiencing some mysterious issues with $(window).width(). When I open my site in the Chrome Device Toolbar with a window size of 320xXXX, then run $(window).width() in Google Chrome's JavaScript console, it returns 980. As a result, n ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...