Display the closest locations on the Google Maps interface

I am currently working on a project that involves integrating Google Maps. The project includes storing hospital addresses (in longitude and latitude) in a database. However, I need assistance in displaying the nearest hospital from my current location. I am having trouble figuring out how to achieve this. Can someone help me with the best algorithm and provide some code examples?

The code below is used to display all hospital addresses on the map. What I now require is guidance on how to show only the 3 nearest hospitals from my current position.

function initMap() {

  var mapType = google.maps.MapTypeId.ROADMAP;
  var animationType = google.maps.Animation.DROP;
  var currentLocationAnimationType = google.maps.Animation.BOUNCE;
  var mapElement = document.getElementById('map');

  var nepalLocation = {
    lat: 28.3949,
    lng: 84.1240
  };
  var mapOptions = {
    center: nepalLocation,
    zoom: 7,
    mapTypeId: mapType,
  };

  // actual map
  map = new google.maps.Map(mapElement, mapOptions);

  var infoWindow = new google.maps.InfoWindow();
  var latlngbounds = new google.maps.LatLngBounds();
  var geocoder = new google.maps.Geocoder();


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(p) {
      var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
      var marker = new google.maps.Marker({
        position: LatLng,
        map: map,
        title: "My Location",
        animation: currentLocationAnimationType
      });
      google.maps.event.addListener(marker, "click", function(e) {
        var infoWindow = new google.maps.InfoWindow();
        infoWindow.setContent(marker.title);
        infoWindow.open(map, marker);
      });
    });
  } else {
    alert('Geo Location feature is not supported in this browser.');
  }

  for (var i = 0; i < markers.length; i++) {
    var data = markers[i]
    var myLatlng = new google.maps.LatLng(data.lat, data.lng);
    var image = "img/iconHospital.png";
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      icon: image,
      title: data.district,
      animation: animationType
    });

  }
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>

<head>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>

<body>
  <div id="map"></div>
</body>

</html>

Answer №1

Check out this demonstration. I modified your code to fit.

function initializeMap() {

  var mapType = google.maps.MapTypeId.ROADMAP;
  var animationType = google.maps.Animation.DROP;
  var currentLocationAnimationType = google.maps.Animation.BOUNCE;
  var mapElement = document.getElementById('map');

  var nepalLocation = {
    lat: 28.3949,
    lng: 84.1240
  };
  var mapOptions = {
    center: nepalLocation,
    zoom: 7,
    mapTypeId: mapType,
  };

  // actual map
  map = new google.maps.Map(mapElement, mapOptions);

  var infoWindow = new google.maps.InfoWindow();
  var latlngbounds = new google.maps.LatLngBounds();
  var geocoder = new google.maps.Geocoder();


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var LatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      var marker = new google.maps.Marker({
        position: LatLng,
        map: map,
        title: "My Location",
        animation: currentLocationAnimationType
      });
      google.maps.event.addListener(marker, "click", function(event) {
        var infoWindow = new google.maps.InfoWindow();
        infoWindow.setContent(marker.title);
        infoWindow.open(map, marker);
      });
    });
  } else {
    alert('Geo Location feature is not supported in this browser.');
  }

  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: nepalLocation,
    radius: 50000,
    type: ['hospital']
  }, placeSearchCallback);
}

function placeSearchCallback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      if (i == 2) {
        break;
      }
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
 
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}
google.maps.event.addDomListener(window, 'load', initializeMap);
<!DOCTYPE html>
<html>

<head>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
  <style>
    
    #map {
      height: 100%;
    }
   
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <div id="map"></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

guide on launching react with pure javascript

Is it feasible to operate react "straight out of the box" using only JavaScript? In essence, I am seeking a way to utilize react by simply utilizing notepad to create the page (without needing to install and configure node etc.). More specifically - 1) ...

Arranging a JSON Object Array in JavaScript by its alphanumeric key attribute order

I need assistance sorting this JSON array by unitId var array = [ { id: 10, unitId: 'unit17' }, { id: 11, unitId: 'unit19' }, { id: 13, unitId: 'unit27' }, { id: 12, unitId: 'unit2' }, { id: 13, unitId: 'unit ...

Generating a JSON object on the fly in a React Native application

There have been similar questions asked in the past like this & this. After looking at those SO questions, I came up with this code. As a newcomer to React Native and Javascript, I am facing two issues. 1. I'm trying to structure my data like this ...

Issue with Jquery firing function during onunload event

I'm having trouble adding a listener to a form in order to trigger an ajax call when the user leaves it. I can't seem to identify any errors in Firefox and nothing is getting logged in the console, indicating that my code might be incorrect. As s ...

Running a 2D JavaScript game script on a React page - A step-by-step guide!

I am facing a challenge with my website that features a game coded entirely in javascript. Despite my efforts to switch the site from an HTML layout to a more modern React design, I can't seem to get the game to display correctly. In the original HTM ...

Who gets the callback when onreadystatechange is triggered in a single-threaded JavaScript environment?

Having recently delved into the world of JavaScript, I've come across the fact that it is single-threaded. My initial assumption was that when making an asynchronous request, a separate thread would be started to monitor the server's response. Ho ...

Displaying a group of elements in ReactJS

I'm currently working on assembling an array using different JSX components. There's a function I've created that populates this array with components and then returns it. let components = []; switch (obj.type) { case 'title': ...

Error message in vuejs: JSON parsing error detected due to an unexpected "<" symbol at the beginning

I have been trying to troubleshoot this issue, but I am having trouble understanding how to resolve it. Currently, I am using lottie-web in a project and need to set the animation parameters on an object in order to pass them as a parameter later. This i ...

Updating DOM elements in AngularJS based on search results and user clicks

I have a query regarding my angular web app, which includes an ajax call for json-formatted dates to display them in a table. The app features a search input, two sorting buttons (for age or name), and a profile sidebar element. I have successfully update ...

Where can the Path be found for Json inside App Phonegap?

Having some trouble with my Phonegap App! Everything seems to be working fine when I test it in my browser. However, once I compile it into an APK and install it on my phone, it's unable to find the JSON data. I'm a beginner in programming and a ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

send array to the sort function

How can I sort a data array that is returned from a function, rather than using a predefined const like in the example below: const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test']; DEFAULT_COMPETITORS.sort(function (a, b) { re ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

Tips for updating server-side variables from the client-side in Next.js

There is a code snippet in api/scraper.js file that I need help with. const request = require("request-promise"); const cheerio = require("cheerio"); let url = "https://crese.org/distintivo-azul/"; let result; request(url, ...

Performing a JSON POST Request: Steps for sending a POST request with JSON data format

I need to send the following data: { "contactsync": { "rev":4, "contacts":[ { "fields": [ { "value": { ...

Exploring Concealed Data and Corresponding in jquery, javascript, and html

A unique template contains 2 hidden fields and 1 checkbox. Using the function addProductImage(), the template is rendered and added to the HTML page. To retrieve the values of the hidden fields (thisFile and mainImage) from a dynamically generated div wit ...

Tips for splitting a container of specific height into sections measuring 80% and 20%

I am working on a container with a fixed position that I want to split into two halves: 80% and 20% at the bottom. This is what I want it to look like: Click here to see the image. Note: The layout should adjust itself when the window is resized. You c ...

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...