Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I've spent two days trying and failing miserably. I thought simply adding rotation: getTrueHeading would do the trick but no such luck.

The only way I managed to get close to what I want is by including the planeSymbol instance and marker instance inside the

setInterval(function() {}, 3000); 

function at the bottom, but this results in duplicating the aircraft icon and seems highly inefficient.

I admit that the code below is not of great quality, so please excuse its shortcomings – I am still learning JavaScript.

If anyone could provide assistance, I would greatly appreciate it.

Answer №1

Extract the heading information from the DOM just like you would with coordinates, and apply it to adjust the rotation property of the icon.

// Obtain the heading value from the DOM
var gettrueHeadingEl = document.getElementById('trueHeading');
getTrueHeading = parseFloat(gettrueHeadingEl.innerHTML);

// Update the rotation property of the icon
marker.setPosition(new google.maps.LatLng(getLat, getLong));
var newIcon = marker.getIcon()
newIcon.rotation = getTrueHeading;
marker.setIcon(newIcon);

Check out the demo fiddle for a visual representation of this concept.

Sample code snippet:

function initMap() {

  var getLatEl = document.getElementById('latitude');
  getLat = parseFloat(getLatEl.innerHTML);

  var getLongEl = document.getElementById('longitude');
  getLong = parseFloat(getLongEl.innerHTML);

  var gettrueHeadingEl = document.getElementById('trueHeading');
  getTrueHeading = parseFloat(gettrueHeadingEl.innerHTML);

  if (isNaN(getLat) == true && isNaN(getLong) == true) {

    // Display default location      
    var usersLocation = {
      lat: 33.949484,
      lng: -118.430566
    };
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: usersLocation,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    });
    var image = 'assets/images/icons/aircraft_marker_map_none_16x16.png';

  } else if (isNaN(getLat) == false && isNaN(getLong) == false) {

    // Show flight sim location
    var usersLocation = {
      lat: getLat,
      lng: getLong
    };
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: usersLocation,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    });
    var image = 'assets/images/icons/aircraft_marker_map_16x16.png';

  }

  var planeSymbol = {
    path: 'M362.985,430.724l-10.248,51.234l62.332,57.969l-3.293,26.145 l-71.345-23.599l-2.001,13.069l-2.057-13.529l-71.278,22.928l-5.762-23.984l64.097-59.271l-8.913-51.359l0.858-114.43 l-21.945-11.338l-189.358,88.76l-1.18-32.262l213.344-180.08l0.875-107.436l7.973-32.005l7.642-12.054l7.377-3.958l9.238,3.65 l6.367,14.925l7.369,30.363v106.375l211.592,182.082l-1.496,32.247l-188.479-90.61l-21.616,10.087l-0.094,115.684',
    scale: 0.0333,
    strokeOpacity: 1,
    color: 'black',
    strokeWeight: 1,
    rotation: getTrueHeading,
    anchor: new google.maps.Point(400, 400)
  };


  var marker = new google.maps.Marker({
    id: "player",
    position: usersLocation,
    map: map,
    title: 'Username',
    icon: planeSymbol

  });

  //
  var polyline = new google.maps.Polyline({
      map: map,
      path: []
    })
    // Move players aircraft
  setInterval(function() {

    var getLatEl = document.getElementById('latitude');
    getLat = parseFloat(getLatEl.innerHTML);
    var getLongEl = document.getElementById('longitude');
    getLong = parseFloat(getLongEl.innerHTML);
    var gettrueHeadingEl = document.getElementById('trueHeading');
    getTrueHeading = parseFloat(gettrueHeadingEl.innerHTML);

    var planeSymbol = {
      path: 'M362.985,430.724l-10.248,51.234l62.332,57.969l-3.293,26.145 l-71.345-23.599l-2.001,13.069l-2.057-13.529l-71.278,22.928l-5.762-23.984l64.097-59.271l-8.913-51.359l0.858-114.43 l-21.945-11.338l-189.358,88.76l-1.18-32.262l213.344-180.08l0.875-107.436l7.973-32.005l7.642-12.054l7.377-3.958l9.238,3.65 l6.367,14.925l7.369,30.363v106.375l211.592,182.082l-1.496,32.247l-188.479-90.61l-21.616,10.087l-0.094,115.684',
      scale: 0.0333,
      strokeOpacity: 1,
      color: 'black',
      strokeWeight: 1,
      rotation: getTrueHeading,
      anchor: new google.maps.Point(400, 400)

    };

    if (marker && marker.setPosition) {
      marker.setPosition(new google.maps.LatLng(getLat, getLong));
      var newIcon = marker.getIcon()
      newIcon.rotation = getTrueHeading;
      marker.setIcon(newIcon);
      polyline.getPath().push(marker.getPosition());
    } else {
      marker = new google.maps.Marker({
        position: usersLocation,
        map: map,
        title: 'Username',
        icon: planeSymbol

      });
    }
    map.panTo(new google.maps.LatLng(getLat, getLong));

  }, 3000);


  marker.setMap(map);
  //  moveAircraft(map, marker);

}
var angle = 0;

function simulateMovement() {
  angle += 1;
  var newPt = google.maps.geometry.spherical.computeOffset(new google.maps.LatLng(42, -72), 100000, angle);
  document.getElementById('latitude').innerHTML = newPt.lat();
  document.getElementById('longitude').innerHTML = newPt.lng();
  var heading = angle + 90;
  document.getElementById('trueHeading').innerHTML = heading;
}
setInterval(simulateMovement, 1000);
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="latitude">42</div>
<div id="longitude">-72</div>
<div id="trueHeading">90</div>
<div id="map"></div>

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

Tips on setting up a self-start event or alert in ASP.NET

I am trying to figure out how to trigger an alert for the user once a specific time has been reached. The challenge is that it cannot be initiated by a button click event or any other action. I want the alert to be displayed even if the user is on a diff ...

This JavaScript function is designed to strip HTML elements from a given

"p" tags are disappearing after running the javascript, but they are needed for structuring purposes. Is there a way to retain the html tags in the hidden/secondary text block even after the javascript manipulation? function AddReadMore() { //This lim ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

How a Dynamic Icon Component in NextJS/React can disrupt Jest testing

Hello there! I'm a new member of this community, and usually I can find answers to my questions by searching. However, this time around, I need some help. My Current Setup I am using NextJS solely as a framework application without utilizing its API ...

Learn the Method Used by Digg to Eliminate "&x=0&y=0" from their Search Results URL

Instead of using a regular submit button, I have implemented an image as the submit button for my search form: <input id="search" type="image" alt="Search" src="/images/searchButton.png" name="" /> However, I encountered an issue in Chrome and Fire ...

Tips on retrieving and refreshing dynamically generated PHP file echo output within a div

I have a div that I'm refreshing using jQuery every 10 seconds. The content is being read from a PHP file named status.php. Here is the JavaScript and HTML for the div: <script> function autoRefresh_div() { $("#ReloadThis").load("status.php ...

Object.assign versus the assignment operator (i.e. =) when working with React components

Just a quick question: I've come across some answers like this one discussing the variances between Object.assign and the assignment operator (i.e. =) and grasp all the points made such as object copying versus address assignment. I'm trying to ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

The HTML element update event was not triggered due to the excessive load of a JavaScript function

I am currently running a JavaScript function that is quite CPU intensive. To provide visual feedback to users when it starts and stops, I am attempting to display a badge on the webpage. Below is the code snippet: function updateView() { console.log(1 ...

Experiencing Excessive Recursion While Dynamically Attaching Click Event Listener With Post Method to a Div Element

I'm encountering 'too much recursion' errors when trying to dynamically add a click handler to specific div tags with the class name 'reportLink'. Despite successfully logging the innerText of the divs, the code fails when attempti ...

The Node/Express Rest API appears to keep directing requests to the same controller function, despite the mappings being correctly

Currently, I am in the process of developing a node/express REST API. When making requests to the following endpoints: http://localhost:5000/api/news and http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80 I noticed that both URLs trigger the same ...

In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary? var arr = '1/1/22'; arr = NTE ...

Error encountered while executing the yarn install command: ENOTFOUND on registry.yarnpkg.com

Typically, when I execute the yarn install command, it goes smoothly without any complications. However, lately, when using the same command, I am encountering the following error: An unexpected error occurred: "https://registry.yarnpkg.com/@babel/core/- ...

Having trouble navigating to the bottom of a VUEJS app?

I've been working on developing a chatbot app that utilizes a REST API to stream content. While the functionality of the app is running smoothly, I have encountered an issue with the scroll to bottom feature. Instead of automatically scrolling to disp ...

Reducing the amount of code within an if statement by utilizing JavaScript

I just finished coding a solution: if(!fs.existSync(path.join(data,file,path)){ fs.mkdirSync(path.join(data,file,path)); } if(!fs.existSync(path.join(another,file)){ fs.mkdirSync(path.join(another,file)); } if(!fs.existSync(path.join(new,file,temp,pa ...

The three.js pointLight has been updated from version 67 to version 68

There appears to be a change in the interaction between a pointlight and a plane from version r.67 to r.68. I am currently studying three.js by following along with a book that is a year old. I have simplified the tutorial example to include just a plane, ...

Issues with Submitting Form using Jquery, PHP, and Mysql

As a beginner, I find this task quite stressful. I want to create a simple chat system where users can send messages to the database without refreshing the page. Why isn't this code working (I've used similar code successfully before)..? <scr ...

VueJs has the ability to display/render a single object from a collection of hundreds of objects at a time

When my API returns hundreds of objects in a response, I want to display only one object at a time on a page. The page includes two buttons - Previous and Next - that allow users to navigate between objects. How can I efficiently manage this data retriev ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...