Bring symbols to life along various geodesic paths

My goal is to animate symbols through multiple geodesic polylines. I have attempted to achieve this using a for loop, but the lines are drawn while the circle (symbol) remains static at the starting point. Below is the code snippet that I've been working on.


var poly;
var geodesic;
var map;
var clickcount = 0;

function initialize() {
    // Map styling and options
    var styles = [{ featureType: "landscape", stylers: [{ color: "#000514"}] }, { featureType: "administrative.country", stylers: [{ weight: 0.1 }, { color: "#009acd"}] }, { featureType: "water", stylers: [{ color: "#1f4fa5dc"}] }, { featureType: "road", stylers: [{ color: "#000514"}] }, { featureType: "administrative.locality", stylers: [{ color: "#7cfc00" }, { visibility: "off"}] }, { featureType: "landscape.man_made", stylers: [{ visibility: "off"}] }, { featureType: "poi", stylers: [{ visibility: "off"}] }, { featureType: "administrative.province", stylers: [{ visibility: "on"}]};
    var mapOptions = {
        center: new google.maps.LatLng(7.3, 80.6333),
        zoom: 3,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setOptions({ styles: styles });

    var lineSymbol = {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 2,
        strokeColor: '#FF0000'
    };

    for (var i = 0; i < 50; i += 5) {
        var flightPlanCoordinates = [
            new google.maps.LatLng(7.3, 80.6333),
            new google.maps.LatLng(23.772323 + i, -102.214897 - i)
        ];
        var polyline = new google.maps.Polyline({
            path: flightPlanCoordinates,
            icons: [{ icon: lineSymbol, offset: '100%'}],
            strokeColor: "#FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 1,
            geodesic: true                  
        });
        polyline.setMap(map);
        animateCircle(polyline);
    }
}

function animateCircle(polyline) {
    var count = 0;
    window.setInterval(function () {
        count = (count + 1) % 200;
        var icons = polyline.get('icons');
        icons[0].offset = (count / 2) + '%';
        polyline.set('icons', icons);
    }, 20);
}

Please assist me with making this animation work as intended. Your help is greatly appreciated. Thank you!

Answer №1

Your polyline variable needs to be accessed outside of the animateCircle function's scope. To achieve this, you should implement a closure by moving the code outside of the animateCircle function and replacing its call with the updated code.

Correction: I made a mistake with the closure as per usual ;-) You can try implementing it like this (once again, not tested):

//variables
var polylines = new Array();

function initialize() {
    //unchanged code

    var i;
    for (i = 0; i < 50; i = i + 5) {
        //unchanged code
        polylines[i] = polyline;
        animateCircle(i);
    }
}

function animateCircle(var id) {
    var count = 0;
    offsetId = window.setInterval(function () {
        count = (count + 1) % 200;

        var icons = polylines[id].get('icons');
        icons[0].offset = (count / 2) + '%';
        polylines[id].set('icons', icons);
    }, 20);
}

Answer №2

After some exploration, I have found a straightforward solution to this issue. Utilizing the Google Maps API v3 has been key in my success. Check out this resource: https://developers.google.com/maps/documentation/javascript/examples/overlay-symbol-animate

To implement this solution, scroll down and select the html+javascript tab. There you will find the variable lineCoordinates. Instead of just 2 objects, we can now pass a set of objects like so:

var lineCoordinates = [
new google.maps.LatLng(latitude1, longitude1),
new google.maps.LatLng(latitude2, longitude2),
new google.maps.LatLng(latitude3, longitude3),
new google.maps.LatLng(latitude4, longitude4)
];

By including multiple objects in lineCoordinates, the animation will occur across all specified points. In the example provided, there are 4 polylines being animated.

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

Loading state with suggestions from autocomplete feature on React

In my current project, I have a component that consists of input fields and a button. The button is set to be disabled until the correct values are entered in the input fields. Everything works as expected, but there's an issue with Chrome auto-fillin ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...

Identifying a Resizable Div that Preserves its Aspect Ratio During Resizing

Below is the HTML code snippet I'm working with: <div id="myid_templates_editor_text_1" class="myid_templates_editor_element myid_templates_editor_text ui-resizable ui-draggable" style="width: 126.79999999999998px; height: 110px; position: absolut ...

What is the best way to add two strings with indexes and points to a Three.js BufferGeometry?

I have a massive database containing tens of thousands of objects with various types of information, including their 3D meshes. Currently, I am attempting to display these objects in web browsers using Three.js. The object information is provided by anoth ...

Prevent form submission by using jQuery's replaceWith method when the input type is a submit button and the onClick event is triggered

Below is the HTML code snippet I am working with: <input class="button" name="save" onclick="$(this).replaceWith('<img src=http://www.example.com/images/ajax-loader.gif />');" type="submit" value="SUBMIT"> After clicking on the butt ...

Retrieving the value of an object based on a dynamic key in Typescript

Currently, I am facing an issue with exporting a single value from a configuration object based on the process.env.NODE_ENV variable. Specifically, I am attempting to retrieve the value of the configEnvs variable like this: configEnvs['local']. H ...

Leveraging the power of Promise creation

I am facing an issue where I am trying to utilize the getPromise function with various URLs in order to obtain different promises, but encountering undefined values in the success function of the second promise. var http=require('http'); var URL ...

How can I manage file input within a Vue.js application?

After attempting to open a file input with a button, I encountered an issue. When clicking the button, the client reported: “this.$refs.image.click”. Below is my code snippet: <v-btn height="50" ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Encountering an issue with npm start when attempting to launch the local host server for a React.js project

Encountering an issue with npm start Error message: 'Equipment' is not recognized as a command, operable program or batch file. internal/modules/cjs/loader.js:983 throw err; ^ Error: Module not found 'C:\Users\Home\Deskto ...

Security ExpoStore malfunctioning (React Native, TypeScript)

I am currently developing a mobile phone application that utilizes Stripe and Expo Bar Code Scanner. Upon launching the application, if camera permissions are granted, users can scan bar codes which contain only the id of the scanned item. If the item exis ...

Combining Context and MUI's theme provider for effective nesting: A step-by-step guide

Currently, I have a state set up to toggle between dark and light mode on a website that contains numerous nested components. The root App.js file looks like this: function App() { return ( <DarkModeProvider> ...

Using Bootstrap4 tagsinput, removing a tag: detecting for AJAX fulfillment and then reversing the action

Utilizing tagsinput in conjunction with bootstrap4, my goal is for the user to be able to delete a tag by clicking on the 'x' button. Upon deletion, an ajax request is sent to the server to verify if the user has permission. The server will respo ...

Exploring the Applications of Directives in Multiple Modules within Angular 2

When I declare the directive in two modules, I get an error that says Type PermissionDirective is part of the declarations of 2 modules. However, when I declare it in only one module, I receive an error stating Can't bind to 'isPermission' s ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

What is the best method for establishing a page location during rendering/onload?

It seems like there is a JavaScript event happening here using the onload attribute. But for the life of me, I can't seem to crack this code. <body onload="moveToHere('reference')"> I'm stuck and could really use some assistance ...

Getting the ng-model value from a Directive's template and passing it to a different HTML file

When working with my name directive, I am unable to retrieve the value of ng-model from the template-url. team-two.html <form name="userForm" novalidate> <div name-directive></div> </form> <pre>{{userForm.firstname}}< ...

What are some effective replacements for SoundManager2 worth considering?

While Soundmanager2 is a useful app, many find the code to be overly complex and difficult to navigate. It almost seems as if it was purposely written in a way to confuse rather than clarify. Are there any recommended alternatives to Soundmanager2 that are ...

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

The drop-down menu selection is non-functional on mobile and iPad devices when using Bootstrap

<div class="panel panel-default"> <select> <option value="B3">B3</option> <option value="B4">B4</option> <option value="B5">B5</option> & ...