Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it.

However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even though the polyline is located in the US.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Polylines</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      // This example creates a 2-pixel-wide red polyline showing the path of
      // the first trans-Pacific flight between Oakland, CA, and Brisbane,
      // Australia which was made by Charles Kingsford Smith.

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 30,
          center: {lat: 38.582692796303924, lng: -89.9953046014092},
          mapTypeId: 'satellite'
        });



          var flightPlanCoordinates = [
              {lat: 38.582692796303924, lng: -89.9953046014092},
              {lat: 38.582663144388235, lng: -89.99447848103262}
            ];

           var flightPath = new google.maps.Polyline({
                    path: flightPlanCoordinates,
                    icons: [{icon: {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW}, offset: '100%'}],
                    geodesic: true,
                    strokeColor: 'red',
                    strokeOpacity: 1.0,
                    strokeWeight: 2
                 });

            flightPath.setMap(map);


              google.maps.event.addListener(flightPath, 'click', function(event) {

                         var arr = this.getPath();
                         
                         console.log(arr.getAt(0).lat() + ', ' + arr.getAt(0).lng());
                         console.log(arr.getAt(1).lat() + ', ' + arr.getAt(1).lng());

                         console.log(event.latLng.lat() + ", " + event.latLng.lng());

            });



        flightPath.setMap(map);
      }
    </script>

   <script src="https://maps.googleapis.com/maps/api/js?key=validkey&libraries=geometry&callback=initMap" async defer></script>


    </script>
  </body>
</html>

To reproduce this problem, please follow these steps:

1) Save the above code in an HTML file and replace "validkey" with a valid Google Maps API key. 
2) Once the map loads, ensure it's at maximum zoom level and in satellite mode. 
3) Open Developer Tools console using F12. 
4) Click somewhere along the polyline. 
5) Three lines will be printed. 

https://i.sstatic.net/xC8Hm.jpg

The last line should display the coordinates of the clicked point, but it inaccurately shows a location in Canada.

Your feedback on this issue would be greatly appreciated. Thank you!

Answer №1

I encountered a similar problem and found a workaround that worked for me.

The issue was with displaying an infowindow at the correct location when clicking on a polyline. Everything worked as expected in aerial view, but in tilted (3D) view, the coordinates were off. Initially, I was using event.latLng within the listener for the polyline click. To resolve this, I decided to update the latLng when in tilted view by setting it to the middle point along the path of the polyline.

Original Code :

google.maps.event.addListener(polyline, 'click', function(event) { 
   openInfoWindow(event.latLng, infoWindowPolyline);
});

Updated Code :

google.maps.event.addListener(polyline, 'click', function(event) { 
   latLng = ((map.getTilt() == 0) ? event.latLng : getMiddlePoint(polyline.getPath()) );
   openInfoWindow(latLng, infoWindowPolyline);
});

function getMiddlePoint(pathArr) {
   const pathLength = pathArr.length;

   let index;
   if (pathLength <= 2) {
       index = 1;
   } else {
       index = Math.ceil(pathArr.length / 2);
   }
   const myLatlng = { lat: pathArr.getAt(index).lat(), lng: pathArr.getAt(index).lng() };
   return myLatlng;
}

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

JavaScript Slider for Color Selection

In my slider, I have added a .images class along with buttons for previous and next. To set the colors, I have used JavaScript to define an array like this: let colors = ['red', 'green',]; Currently, clicking the next-button displays ...

Error in Express JS: Attempting to access properties of an undefined variable (reading '0'). Issue with SQL query

Struggling to insert something in my database and then access it directly after. Due to the asynchronous nature of node.js, my plan doesn't seem to work out. However, I am confident that there is a solution to make this happen. Here's the code sn ...

React Router relies on a DOM for Browser History to function properly

I am currently developing my app using React.js and express. My main focus right now is setting up react-router-dom for the application. Unfortunately, I encountered a warning when attempting to run the app: Invariant Violation: Browser history needs a ...

Contrasting methods of adding a value to an array state in React

Can you advise me on the most effective method for inserting a value into an array, as well as explain the distinctions between these two code examples? setOtoValue((current) => [ ...current, Buffer.from(arraybuf, 'binary').toString(' ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

Exploring VueJS reactivity: Updating an array with new data

I am struggling to understand why certain methods of changing data seem to work while others do not. In an attempt to clarify, I experimented with the following example: watch: { '$store.state.linedata': function() {this.redraw()} } ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

Is there an equivalent to Tomcat specifically designed for Node.js applications?

Looking for an application server that offers an administration interface to deploy node.js applications, access log files, and manage running applications with options to start, stop, restart, and monitor? ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

Creating an href link within a button that is contained within a collapse component

I am grappling with an issue where my collapsed model is displaying more information about clients; however, when I click on the button inside it, instead of getting the specific client's data, I end up retrieving information for all clients. <ion ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Eliminate redundant entries from an Ionic3 array

Looking for a solution to eliminate duplicate values in the storage array within Ionic3 this.storage.get('thestations').then((val) => { for(let i =0;i<val.length;i++){ if(this.newarray.indexOf(this.newarray) == -1) ...

Does angular-sortablejs work with angular 5?

I attempted to use angular-sortables in combination with the ng-drag-drop library to sort the list items that are being dragged, but it appears that nothing is happening when I try to use it. Does anyone know if angular-sortables is compatible with Angular ...

Different boolean variable assigned to every item in v-for loop

I am working on creating a custom play/pause button for my audio elements, and here is how I have implemented it: <div v-for="(post, p) in post_list"> <!-- ... --> <!-- ... --> <!-- ... --> <v-avatar v-i ...

issue with for loop in jquery ajax not processing complete response data

I have a total of 9 columns in my table, namely choosen_emails_1, choosen_emails_2, choosen_emails_3, booking_address, booking_number, booking_message, booking_date, request_date & user_email The for loop is programmed to iterate and display all colum ...

Node.JS executes Sandbox within a RESTful service environment

Utilizing the Node Restify Module to develop a REST service that accepts POST requests. Inside the service, I am attempting to create a Sandboxed process using the Node Sandbox module in order to execute dynamically inserted JavaScript without impacting th ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

The blend of Combination and Advanced Timeline triggers a "ReferenceError: Highcharts is not defined" error

Replication Steps First, download HIGHCHARTS 4.1.9 from http://www.highcharts.com/download Next, open the file index.html Then, click on Combinations > Advanced timeline An error message is displayed in Firebug and the chart does not appear: Referenc ...