Exploring the Google Maps API Search feature

I am currently developing a JavaScript application that interfaces with the Google Maps API. The program has the following requirements:

  1. Enable users to input a location.
  2. Upon clicking the "find" button, convert the user's entered location into longitude and latitude coordinates.
  3. Run an algorithm to calculate the distance between the user's entered location and 20 predefined longitude and latitude coordinates.
  4. Display the calculated distance in kilometers.
  5. Identify the location with the shortest distance by looping through and comparing all distances.

I have successfully completed steps 1 and 2, but I am struggling to identify a method for storing the index of a location, including its longitude and latitude points. This is crucial for comparing them to the user-inputted location. Additionally, I am having difficulty devising a strategy for determining the shortest distance among all points to find the closest longitude and latitude.

Any assistance would be greatly appreciated,

THANK YOU!

Answer №1

I believe this solution can be easily tweaked to suit your specific needs.

//function for computing distances between two points
var calculateDistance = function(point1, point2) {
  var radian = function(x) {return x*Math.PI/180;}
  var R = 6371; // average radius of the Earth in kilometers
  var dLat  = radian(point2.lat() - point1.lat());
  var dLong = radian(point2.lng() - point1.lng());

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(radian(point1.lat())) * Math.cos(radian(point2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var distance = R * c;

  return distance.toFixed(3);
}

// defining LatLng object with current coordinates
var currentPosition = new google.maps.LatLng(yourlat, yourlng);

// creating an array of hard coded LatLng objects 
var twentyPoints = {};
twentyPoints['name1'] = new google.maps.LatLng(lat1, lng1);
twentyPoints['name2'] = new google.maps.LatLng(lat2, lng2);
twentyPoints['name3'] = new google.maps.LatLng(lat3, lng3);
  ...

// finding the closest location
var closestLocationName, minDistance;
for (var name in twentyPoints) {
  tempMinDistance = calculateDistance(twentyPoints[name], currentPosition);
  if (minDistance === undefined || tempMinDistance < minDistance) {
    minDistance = tempMinDistance;
    closestLocationName = name;
  }
}

console.log('The nearest location is named ' + closestLocationName + '.');
console.log('It is ' + minDistance + 'km away.');

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

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Experiencing a 403 Error while using request-promise to extract price data from a website

My current challenge involves using request-promise to scrape the price of an item from Asos.com. Whenever I try to execute the code provided below, I encounter a 403 error. Could it be possible for this error to occur even though the URL I am attempting t ...

Load the page using AJAX and automatically scroll to the anchor within the loaded content

I want to achieve an automatic scroll to the beginning of a loaded page after using ajax to load it. Here is the code snippet I currently have: html <button class="btn btn-info btn-lg" type="button" id="photos"> <i class="fa fa-plus fa-5x">&l ...

A step-by-step guide on disabling Google Analytics in a Next.js document.js file

Upon a user's initial visit to the website, they are presented with the option to either accept or decline tracking cookies. If the user declines, a cookie is set with the value of false. I am in need of a way to conditionally run the gtag script base ...

Importing modules using relative paths results in failure due to module not being found, whereas employing absolute paths

I have been encountering this problem for a considerable amount of time and have made multiple attempts to resolve it. I am currently working on the development of my discord.js bot and recently switched from TS back to JS due to certain complications I fa ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

What steps should I take to enable this SimpleModal to load automatically?

Is there a way to have the SimpleModal script load when the page loads instead of having to click a button? Thank you for your help! < div id='basic-modal' > <a href='#' class='basic'>Demo</a> </div> ...

What is the best way to save a series of values into separate arrays and then combine them together in VBA?

I am fairly new to VBA and struggling to effectively manipulate range and array values. Currently, I am working on a user form where I need to merge the values from two user-provided ranges into a single array for sorting purposes, followed by using them ...

Is there a definitive way to distinguish between scrollTop and scrollHeight in web development?

For instance, function checkingScroll(){ var newHeight = element.scrollHeight; var scrollTopValue = element.scrollTop; alert("The scrollHeight property is: " + newHeight + "px"); alert("The scrollTop property is: " + scrollTopValue ...

Uncovering the key based on the value in MongoDB

I'm currently working with Node.js using the express framework and Mongoose for MongoDB, and I've got a query regarding efficient data retrieval. Imagine having a mongo document structured like this: test : {a:1, b:2, c:2, d:1}; While it' ...

Internet Explorer failing to trigger Ajax requests

I'm encountering an issue with my script on my webpage - it works perfectly in Chrome, but Internet Explorer is not entering the success{} function of Ajax. It does go into the Complete{} function without any problems. I attempted to pass the data var ...

Is there a way to launch Visual Studio Code using a web browser?

Is there a way to launch "Visual Studio Code" automatically upon clicking a button on my website? ...

Exploring the Factory Design Pattern Together with Dependency Injection in Angular

I'm currently implementing the factory design pattern in Angular, but I feel like I might be missing something or perhaps there's a more efficient approach. My current setup involves a factory that returns a specific car class based on user input ...

Dispatching information to a designated Google Analytics tracking code

Within our website, we have a unique dimension that is configured on Google Analytics and utilized when sending the page view event: gtag('config', 'UA-TrackingCode', { 'custom_map': { 'dimension1': &apo ...

Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two l ...

AngularJS Update Parent-Child Relationship: Enhancing the Details

When Panel header is clicked, I want to update the respective Panel body with the corresponding data. In my Angular code on Plunker, clicking "Test1" should only update "Test1detail" in the body. Click here for the Plunker Here's the code snippet fr ...

Using jQuery to automatically select a specific radio button after the load() function is executed

I'm trying to dynamically load radio buttons into a div using the JQuery load() function. However, I'm facing an issue when it comes to checking a specific radio button by its value. The problem is that the code doesn't seem to be working w ...

An issue has been encountered with the Vue Router within the Micro Front End/Web Components setup, displaying the error message: "Uncaught TypeError:

I encountered an issue that I need help with. Here is the scenario: I have built a Vue application called my-admin micro app consisting of 4-5 screens/components (manage user, manage notifications, manage roles, etc.). I created a router.js file where I d ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...