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

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...

Issue with JavaScript Date.parse function not functioning as expected

I have implemented a date validation method in my application to check if a given date is valid or not. myApp.isValidDate = function(date) { var timestamp; timestamp = Date.parse(date); if (isNaN(timestamp) === false) { return true; } return ...

Finding JPG images using Jquery selector

I am looking to utilize jQuery to specifically target <a href=""> elements that have 'href' attributes with file extensions '.JPG' or '.jpg' For instance: To only select these 'links' <a target=& ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Struggling to update local state with response data when utilizing hooks in React

I am a beginner using Functional components and encountering an issue with setting the response from an API to a local useState variable. Despite receiving the response successfully, the variable remains empty and I am struggling to figure out how to resol ...

How can I utilize ng-repeat in AngularJS to iterate through an array of objects containing nested arrays within a field?

Here is the structure of an array I am working with: 0: {ID: null, name: "test", city: "Austin", UserColors: [{color: "blue"},{hobby:"beach"} ... ]} }... I am currently attempting to ng-repeat over this initial array in my code. However, when I tr ...

The spring controller sends back HTML content

Currently, I am working on a project involving Spring MVC, Liferay, and jQuery. One issue that I am facing is related to an ajax request (post) which calls a controller method annotated with @ActionMapping. When the ajax callback function is triggered, th ...

Accessing an array from another method within the JavaScript class

Hello everyone, I am new to JavaScript and have a question about calling an array from another function within the same class. Here is an example code snippet: class Something { constructor () {} async functionA () { this.list = [] } a ...

Retrieve a remote text file using vanilla JavaScript instead of relying on jQuery

Currently, I am aiming to retrieve the content of a text file using JavaScript for parsing purposes. Although I previously relied on jQuery and JSONP for this task, I now prefer to achieve it without any framework. Despite numerous attempts, none have bee ...

jquery is unable to locate text

UPDATE: I have recently implemented a function that calculates and displays the length of a certain element, but it currently requires user interaction to trigger it: function check() { alert($("#currentTechnicalPositions").html().length); } After s ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

links to css and javascript

I am having trouble with what should be a simple task! On my webpage, I have this link: <a class='action' href='javascript:void(0)' OnClick='run()'> run </a> Along with the following CSS: .action { color: # ...

The functionality of "Priority Nav" is compromised when a div is floated

I am currently utilizing the "Priority Navigation" design technique. This means that when the viewport width is reduced and there isn't enough space for all the list-items to fit horizontally, they are moved into another nested list under a "more" lin ...

Unable to upload file to firebase storage - encountering technical issues

After following the documentation on firebase storage, I still can't seem to get my file upload to work properly. Using react, my goal is to successfully upload a file to firebase storage. However, I keep encountering an error message: TypeError: th ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Encountering the message "Error: Unable to access undefined properties (reading 'username')" while making my POST request

My POST request isn't functioning correctly and it's failing to update. The specific error message I'm encountering is: TypeError: Cannot read properties of undefined (reading 'username') app.post('/create-user', functio ...