How far is the Google Maps Marker Distance?

I am interested in knowing how I can calculate the distance between my current location and a marker on the map, taking into account the curvature of the earth. Below is my JavaScript code:

var map;
function initMap(){
//constructor creates a new map - only center and zoom are required
map = new google.maps.Map(document.getElementById('map'),{
    center: {lat: 45.325187, lng: -66.2113336},
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var markers = [];

var locations = [
    {title: 'Ethan House', location:{lat: 45.3631979, lng: -66.2118715}},
    {title: 'Josh House', location:{lat: 45.379291, lng: -66.2199817}},
    {title: 'Luke House', location:{lat: 45.2420391, lng: -66.1485755}},
    {title: 'Jack House', location:{lat: 45.3262894, lng: -66.189719}}
];

var largeInfoWindow = new google.maps.InfoWindow();

//uses location array to create an array of markers on init
for (var i = 0; i < locations.length ;i++) {
    //get the position from locations array
    var position = locations[i].location;
    var title = locations[i].title;
    //Create marker per location and put into markers array
    var marker = new google.maps.Marker({
        map: map,
        position: position,
        title: title,
        animation: google.maps.Animation.DROP,
        id: i
    });
    //Push marker into array of markers
    markers.push(marker);

    //Create an onclick event to open an InfoWindow for each marker
    marker.addListener('click', function(){
        populateInfoWindow(this, largeInfoWindow);
    });
}

document.getElementById('show-listings').addEventListener('click', showListings);
document.getElementById('hide-listings').addEventListener('click', hideListings);




//This function populates the InfoWindow when the marker is clicked
//only allow one InfoWindow which will open at the marker that is clicked
//and populate based on the markers position.
function populateInfoWindow(marker, infowindow){
    //check to make sure the infowindow is not already opened on this marker
    if(infowindow.marker != marker){
        infowindow.marker = marker;
        infowindow.setContent('<div>' + marker.title + '</div>');
        infowindow.open(map, marker);
        //make sure the marker property is cleared if the InfoWindow is closed
        infowindow.addListener('closeclick', function(){
            infowindow.setMarker(null);
        });
    }

}

//This function will loop through the markers array and display them all
function showListings(){
    for(var i = 0; i < markers.length; i++){
        markers[i].setMap(map);
    }
}

//This function will loop through listings and hide them all
function hideListings(){
    for(var i = 0; i < markers.length; i++){
        markers[i].setMap(null);
    }
}

//Check if user supports geo-location
if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var geolocalpoint = new google.maps.LatLng(latitude, longitude);
        map.setCenter(geolocalpoint);

        var mapOptions = {
            zoom: 8,
            center: geolocalpoint,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        //Place a marker
        var geolocation = new google.maps.Marker({
            position: geolocalpoint,
            map: map,
            title: 'Your geolocation',
            icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
        });
    });
}

}

Answer №1

Are you looking for a route from your current position to a specific marker, or just the distance between them?

If you only need the distance, you can employ the haversine formula to calculate the direct distance between two sets of coordinates (as the crow flies).

Check out this JavaScript example (Source):

var R = 6371e3; // meters
var lat1Radians = lat1.toRadians();
var lat2Radians = lat2.toRadians();
var deltaLat = (lat2-lat1).toRadians();
var deltaLon = (lon2-lon1).toRadians();

var a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
        Math.cos(lat1Radians) * Math.cos(lat2Radians) *
        Math.sin(deltaLon/2) * Math.sin(deltaLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

var d = R * c;

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 configuring formik values

index.js const [formData, setFormData] = useState({ product_name: 'Apple', categoryId: '12345', description: 'Fresh and juicy apple', link: 'www.apple.com' }); const loadFormValues = async () => { ...

Getting PHP Post data into a jQuery ajax request can be achieved by using the `$_POST

I'm struggling to figure out how to pass the blog title into the data field of my ajax call. I've been searching for beginner tutorials on SQL, PHP, and AJAX, but haven't found anything that clarifies this issue. If anyone knows of any usefu ...

Update the sum upon deleting a feature in an HTML and JavaScript form

Once a row or field is added, this function will display a delete link. When clicked, it will remove the row or field: var ct = 1; function addNewRow(){ ct++; var divElement = document.createElement('div'); divElement.id = ct; // Code to cr ...

Utilizing the power of functional programming with Javascript to perform mapping

In order to address a fundamental issue involving list indexes, I am seeking a functional solution. To illustrate this problem in the context of React and ramda, consider the following example. const R = require('ramda'); const array = ["foo", ...

Data is not being stored in the MongoDB Model/Schema as expected

I'm encountering an issue with my MongoDB database. It appears to not be receiving the data I am attempting to send to it, resulting in an empty database despite everything else functioning smoothly. The application I'm working on involves scrap ...

Leveraging AJAX to call upon a designated php file

I have a selection of menu items on my webpage, each with different options: option1, option2, and option3. Additionally, I have corresponding PHP files on my server for each of these menu items: option1.php, option2.php, and option3.php. For simplicity, ...

JQuery - stylish vertical accordion navigation menu

I'm currently working on a vertical accordion-style sidebar navigation system. Everything seems to be functioning properly, but I've encountered some issues with the icons that I'm using from Twitter Bootstrap 3. You can view the code on th ...

Curious as to why JavaScript restricts the use of two variables entering at the same time

Currently, I am tackling an Ajax-php livesearch programming challenge. I am facing an issue where JavaScript is unable to receive the values of 2 parameters that I want to input in HTML input boxes. Any idea why this might be happening? This is my HTML co ...

There seems to be a problem with the bundle.js file caused by Uglify

I've just finished a project and now I'm ready to start building it. Utilizing a boilerplate project, I still find myself struggling to comprehend all the npm/webpack intricacies happening behind the scenes. Whenever I try to run "npm start", I k ...

Show a row of pictures with overflow capabilities

I am looking to develop my own image viewer that surpasses the capabilities of Windows. My goal is to design an HTML page featuring all my images laid out horizontally to maximize screen space. I also want the images to adjust in size and alignment as I z ...

utilizing the angularjs $scope variable within a jquery bind method

I recently implemented the Fullcalender directive in my AngularJS application. While I was going through the documentation, I noticed that there is a double click handler available in the Fullcalender jQuery plugin. For reference: http://code.google.com/p ...

Using a form tag within a table in HTML5

Can someone help me figure out how to integrate a form with the "Get" method into a table? The table includes a text field, and upon submitting the form, it should initiate validation. The validation process currently works correctly, however, when submi ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

Toggle the visibility of a component in React by managing its state

Currently, I am faced with the challenge of toggling the visibility of a component based on a state value: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Button from ' ...

To properly conduct Playwright Component testing, it is essential to utilize the defineConfig() function

Currently, I am utilizing Playwright to execute tests on my components. The installation of playwright was completed by using the following command: npm init playwright@latest -- --ct Below is the configuration file for playwright-ct: import { defineConf ...

Is there a way to determine the dimensions of a pdf file using javascript and capture a snapshot of it for showcasing on a website?

I'm fairly new to HTML/CSS and haven't delved into javascript yet, but I have a good understanding of reading other people's code. Currently, I'm putting together my portfolio website and would like to include my resume on the page in a ...

the conditional operator used without assigning the result to a variable

Exploring conditional operators on html canvas, I am seeking a streamlined approach to dynamically change stroke color based on conditions. Online examples have not provided a satisfactory solution in a single line of code. Currently, without using a cond ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Ways to verify if an email has been viewed through the client-side perspective

How can I determine if an email has been read on the client side using PHP? I need to verify if emails sent by me have been opened by recipients on their end. Additionally, I would like to extract the following details from the client's machine: 1. ...

The issue with importing data into Google Sheets due to an error with Ljava

After combining different scripts, I am struggling to properly input data into the code. Email Input: *Status:* *Date:* 03/31/2020 *WorkOrder:* 123456-1 *DMSShipDate:* 03/31/2020 *PONumber:* 8675309 *Company:* Test New Script var ui = SpreadsheetApp.g ...