Show the latitude and longitude coordinates when the user clicks the mouse using JavaScript

I am currently working on a project using javascript to display the current location of a user on a map. I am trying to add a listener for when the user clicks on the map to show the latitude and longitude coordinates. However, my code is not working as expected. I suspect that I may have made a mistake somewhere. Can someone please help me identify what is wrong with my code:

  <script src="http://maps.google.com/maps/api/js?sensor=false">
</script>

<script type="text/javascript">
    var map;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var coords = new google.maps.LatLng(latitude, longitude);
            var mapOptions = {
                zoom: 15,
                center: coords,
                mapTypeControl: true,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.SMALL
                },
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(
            document.getElementById("mapContainer"), mapOptions
            );
            var marker = new google.maps.Marker({
                position: coords,
                map: map,
                title: "Your current location!"
            });

        });
    } else {
        alert("Geolocation API is not supported in your browser.");
    }

    function setUpClickListener(map) {
        // Attach an event listener to map display
        // obtain the coordinates and display in an alert box.
        map.addEventListener('tap', function (evt) {
            var coord = map.screenToGeo(evt.currentPointer.viewportX,
                evt.currentPointer.viewportY);
            alert('Clicked at ' + Math.abs(coord.lat.toFixed(4)) +
                ((coord.lat > 0) ? 'N' : 'S') +
                ' ' + Math.abs(coord.lng.toFixed(4)) +
                ((coord.lng > 0) ? 'E' : 'W'));
        });
    }

    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));

    setUpClickListener(map);
</script>
<style type="text/css">
    #mapContainer
    {
        height: 500px;
        width: 800px;
        border: 10px solid #eaeaea;
    }
</style>
<div id="mapContainer">
</div>

Answer №1

function coord.lat() should be used to retrieve both the latitude and longitude values, with coord.lat().toFixed(4) being the proper syntax.

Answer №2

If you are looking for a way to handle user interaction in Google Maps, please note that the 'tap' event is not supported. Check out the Events documentation for alternatives.

One option is to use the following code snippet:

map.addListener('click', function(evt) {
  var lat = evt.latLng.lat();
  var lng = evt.latLng.lng();
  // ... Customize your action based on the latitude and longitude values here....
});

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 for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Exception Thrown When Selenium Element is Not Visible After Being Triggered in a Specific Area

I'm currently working on automating entries for this giveaway hosted on: My progress so far includes successfully clicking on the "Visit @nexi_tech on Instagram" link and the subsequent blue button. I then face an issue when trying to interact with t ...

Facing Hurdles in Starting my Debut Titanium Mobile Project

I recently started using Titanium Studio (version 2.1.0GA on WindowsXP) and I have added the Android SDK to it. However, I am encountering an error when trying to run my first mobile project. The console is displaying the following message: Can anyone off ...

Problem with Marionette AppRouter compatibility when used with Browserify

app.js module.exports = function () { if (!window.__medicineManager) { var Backbone = require('backbone'); var Marionette = require('backbone.marionette'); var MedicineManager = new Marionette.Application(); Medicin ...

Duplicating a concealed div and transferring it to a new div

I'm encountering an issue while trying to copy one div to another. The div I'm attempting to copy has a hidden parent div. The problem is that the destination div does not appear after copying, even though I changed its style display to block. ...

Ensure the most recently expanded item appears at the top of the TreeView by updating to Mui version

I'm working on a feature where I want to scroll the expanded TreeItem to the top when it has children and is clicked on for expansion. Any suggestions on how to make this happen? ...

Filter out discord messages for deletion

A script was created to automatically delete messages from offline users during chat sessions on Discord. If an offline user attempted to chat, their message would be deleted, and a notification would be sent to the console indicating that offline chat was ...

Setting up Highcharts version 7 heatmaps with npm in an Angular 6 environment

I am currently having an issue with initializing the heatmap lib in Highcharts 7.0.1 within my Angular 6 app via npm. Despite successfully running basic charts like line, spline, bar, etc., when following the documentation for the heatmap initialization, I ...

A TypeScript example showcasing a nested for-of loop within several other for loops

Is it possible to generate values from an Array of objects in the following way? const arr = [ { type: "color", values: [ { name: "Color", option: "Black", }, { name: "C ...

ignite asp.net CustomValidator

I am facing an issue with a password input that has a customValidator. Whenever I modify the value of the password, it checks if the password contains the name. Now, I also need to trigger the same customValidator (client-side validation) when I edit th ...

Tips for developing a function that can identify the position of the largest integer within a given array

I need some help refining my function that is designed to identify the index of the largest number in an array. Unfortunately, my current implementation breaks when it encounters negative numbers within the array. Here's the code snippet I've bee ...

Angular Express encountering URL mismatch when retrieving files post-refresh

Currently, I am developing a small MEAN stack application. One of the features is that when an image is clicked, it displays a partial containing information about the image. Everything was working fine initially. However, after refreshing the page, Angula ...

Fill the dropdown menu with options in real-time

I am working on a page that involves populating two dropdown lists with items from SQL Server during the Page_Load event. This process can take some time, causing the page loading to slow down. Currently, I have implemented asynchronous loading for the d ...

Switching an application from Angular 5 to Angular 8 can lead to unexpected styling problems

My current project is based on Angular version 5.2, but we recently decided to upgrade it to Angular 8 along with updating the Angular CLI. After completing the necessary code refactoring for Angular 8, the application builds successfully without any error ...

Issue with primeng dropdown not displaying the selected label

When using the editable dropdown with filter feature from PrimeFaces, I've noticed that selecting an option displays the value instead of the label. https://i.sstatic.net/8YFRa.png Here is the code snippet: <div class="col-md-5 col-xs-1 ...

Show validation messages using ng-messages depending on various conditions

Implementing angular ng-messages for validation message display Check out this code snippet: <ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple> <li ng-message="pattern">Invalid pattern</li> <li ng-m ...

What is the best way to securely map backend data following a request?

Let me start by mentioning that this particular situation can also occur in the opposite manner as well. Situation: Imagine a scenario where the backend developer, who is not really your friend :D, defines a DTO (send JSON) with properties, for instance ...

HTML Master Page - Working on eliminating empty space

While working on my ASP.NET project for class, I seem to be encountering an issue with a mysterious blank space. Despite checking for breaks, margins, and padding throughout the code, I can't pinpoint the source of this unwanted gap. The blank space a ...

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...