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. 

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

"Bringing together ECMA harmony: a nod to callbacks and generators

Initially, we are exploring uncharted territory here. Although it functions in the latest versions of Firefox, the documentation on MDN is not yet ready at the time of writing. I will address the MDN later on (maybe, as there are numerous areas needing att ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...

Tips for showing data from Ajax responses on an HTML page

In my code, there are two JavaScript functions: The function fetch_items is responsible for returning data in the form of stringvalue. On the other hand, the function extract_items($arr) passes values to the fetch_items function. function fetch_items ...

How can I customize the appearance of the container and items in a dropdown <select> menu?

Im using contact form 7 on wordpress, i don't want to use a plugin rather use plain css/js to bring the results if possible. Something like this : https://i.stack.imgur.com/VTWRg.jpg ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

Issue: The function (0, react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not recognized as a valid function or its output is not iterable

I found a great example of using useActionState at this source. Currently, I am implementing it in my project with Next.js and TypeScript. app/page.tsx: "use client"; import { useActionState } from "react"; import { createUser } from ...

Puppeteer: Interacting with login dialog box fields

I am currently facing an issue while attempting to generate a .pdf file from a specific page on our Intranet using Puppeteer and Headless Chrome within Node.js. Generating a .pdf file from a regular webpage poses no challenge, but I am encountering diffic ...

Show information according to the selection made in the dropdown menu

Greetings! I am currently developing a web app using MVC .NET (C#) that includes a registration page for two types of users, type 1 and type 2. In the form, there is a dropdown list where users can select their type. When selecting type 2, I would like t ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

How can I ensure that Chakra UI MenuList items are always visible on the screen?

Currently, I am utilizing Chakra UI to design a menu and here is what I have so far: <Menu> <MenuButton>hover over this</MenuButton> <MenuList> <Flex>To show/hide this</Flex> </MenuList> </ ...

How to display a div in Angular when hovering with ElementRef and Query List

I am having trouble implementing a ngFor loop in my project where I want to display a div on mouse hover using the @Input notation. This is how my HTML code looks: <div class="col s12 m6" style="position: relative" *ngFor="let res of hostInfo.resident ...

Understanding the impact of event loop blocking and the power of asynchronous programming in Node JS

I am new to Node.js programming and I really want to grasp the core concepts and best practices thoroughly. From what I understand, Node.js has non-blocking I/O which allows disk and other operations to run asynchronously while JavaScript runs in a single ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

Retrieving data sent through an AJAX post request

My current project involves making a POST call from a basic HTML page to a Node.js and Express server that will then save the input values to a MongoDB collection. The issue I am facing is that when passing two POST parameters, namely 'name' and ...

The Firebase signInWithPopup functionality suddenly shuts down in a Next.js project

Incorporating the signInWithPopup function for signing in has been successful during the development stage on my local server. const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user, cartShow, cartItems }, dispatc ...

`Accessing information within a nested JSON array``

I'm currently parsing through the JSON data below. While I can extract the id and name fields without any issues, I am encountering a problem when trying to access json.templates[i].dailyemails.length, as it always returns 0. Below is the structure o ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Pattern matching to verify a basic number within the range of [0-6]

const number = '731231'; const myRegex = /[0-6]/; console.log(myRegex.test(number)); Could someone provide some insight into this code snippet? In my opinion, the regular expression [0-6] should only match numbers between 0 and 6. However, i ...

"Learn how to dynamically update the user interface in express.js using handlebars without having to refresh the

As a newcomer to using express.js and Handlebars, I am faced with the challenge of implementing autocomplete functionality. Specifically, I want to enable autocompletion in a text input field without triggering a page refresh when users interact with it. C ...