Manipulating latitude and longitude variables from Javascript Geolocation in an ASP.NET environment

Attempting to retrieve user location using geolocation in JavaScript, I am able to see the current location. However, when trying to assign the coordinates variable to a C# object label, it does not return anything. Below is my JavaScript code snippet:

  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=ABC"></script>
    <script type="text/javascript">
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (p) {
                var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
                var mapOptions = {
                    center: LatLng,
                    zoom: 20,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
                var marker = new google.maps.Marker({
                    position: LatLng,
                    map: map,
                    title: "<div style='height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude,

                });
                google.maps.event.addListener(marker, "click", function (e) {
                    var infoWindow = new google.maps.InfoWindow();
                    infoWindow.setContent(marker.title);
                    infoWindow.open(map, marker);
                  //  document.getElementById("latitude").value = p.coords.latitude;
                 //   document.getElementById("longitude").value = p.coords.latitude;
                });

                var longitude = document.getElementById('latitude'),
                    latitude =  document.getElementById('longitude');
                function GetPosition(p) {
                    var long = p.coords.longitude,
                        lat = p.coords.latitude
                    longitude.text(long);
                    latitude.text(lat);
                }
            });
        } else {
            alert('Location feature is not supported in this browser.');
        }
    </script></code></pre>
</div>
</div>
</p>

<p>The body section is as follows:</p>

<p><div>
<div>
<pre><code> <div>
            <div id="dvMap" style="width: 500px; height: 500px"></div>
            <asp:Label ID="latitude" runat="server"></asp:Label>
            <asp:Label ID="longitude" runat="server"></asp:Label>
        </div>

Tried using GeoCoordinateWatcher without success. Is there an alternative method to acquire user location? Appreciate your help.

Answer №1

@NAJEEB, Take a look at the solution provided below

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=ABC&callback=myMap"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      var longitude = $('#longitude');
       var latitude = $('#latitude');
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (p) {
             console.log(longitude);
                    longitude.text(p.coords.longitude);
                    latitude.text(p.coords.latitude);
                var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);

                var mapOptions = {
                    center: LatLng,
                    zoom: 20,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
                var marker = new google.maps.Marker({
                    position: LatLng,
                    map: map,
                    title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude,

                });
                google.maps.event.addListener(marker, "click", function (e)                 {
                    var infoWindow = new google.maps.InfoWindow();
                    infoWindow.setContent(marker.title);
                    infoWindow.open(map, marker);
                });
            });
        } else {
            alert('Location feature is not supported in this browser.');
        }
        });
    </script>
<title>Page Title</title>
</head>
<body>
 <div>
  <label ID="latitude"></label>
 <label ID="longitude"></label>
 <br/>
 <div id="dvMap" style="width: 500px; height: 500px"></div>
 </div>
</body>
</html>

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

Error: Unable to locate module: "./library". The parent module directory is "/"

I keep encountering an issue in my project when attempting to load a module. Whenever I try to import it from the node_modules folder, I receive the following error: Uncaught Error: Module not found: "./MyLibrary". Parent module folder was: "/" However, i ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

How can I implement the vm. syntax using ControllerAs in my application?

After reading various sources, including a few discussions on Stack Overflow, I have come to understand that the ControllerAs syntax is gaining popularity as it aligns with how things are done in Angular 2. Therefore, I decided to delve deeper into unders ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

You must pass a string, Buffer, ArrayBuffer, or Array as the first argument when using Uint8Array.slice(). A number was received instead

Here is my implementation of the ByteArray class, which extends the Uint8Array class. export class ByteArray extends Uint8Array { ... private _encoded: string; ... constructor(_encoded: string) { super(Buffer.from(_encoded, " ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Guide on launching a new URL from Action within an MVC controller

Is there a way to redirect to an external URL with a new window from a controller in an ASP.NET MVC / C# app? While it's easy if the requirement is within the view, I'm facing the challenge since this involves the controller. In my scenario, I ...

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...

Customize Swiper js: How to adjust the Gap Size Between Slides using rem, em, or %?

Is there a way to adjust the spacing between slides in Swiper js using relative units such as 2rem? The entire page is designed with relative units. All measurements are set in rem, which adjusts based on the viewport size for optimal adaptability. For i ...

Implementing a JSON array to object conversion in an Express REST API

After conducting a test on a REST API using Postman, the outcome was as follows: { "success": true, "message": "success", "data": [ { "id_buku": 9, "judul_bu ...

Error code received from OpenStack Identity API GET response

I am an intern student and I have a query. Currently, I am working on bug fixing for an Openstack cloud, JavaScript, and Node.js web application. My task involves resolving toastr.error messages and translating them into different languages. How do I ret ...

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

What is the best way to add a new item to an object using its index value?

Can the Locations object have a new property added to it? The property to be added is: 2:{ name: "Japan", lat: 36, lng: 138, description: 'default', color: 'default', url: 'default' } The current Location ...

Using jQuery to smoothly scroll to a specific class name

I am faced with an HTML code snippet that looks like this: <div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div> My intention is to use jQuery to scroll to the game number 456 as shown below. var contain ...

Determine if a cookie is set in Vue.js without requiring a page refresh

My current goal with VUE is to make the login url disappear from the navigation bar as soon as the user logs in. After successfully logging in, the token cookie is set in the browser. However, the issue arises when the login url remains visible in the nav ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...

Tips for passing parent component state data to a child component using a variable

In my index.js file, I have a parent component with a state variable x:[] that contains data [{…}, {…}, {…}]. Now, in my child component (child.jsx), I need to save this parent component data [{…}, {…}, {…}] in a variable within the child compo ...