Get coordinates, measure distances and compare them

Asked

Viewed 1,663 times

1

I was proposed to develop a page where this presents an excerpt from Google Maps with several markers organized in clusters (done).
I have no experience with Javascript, and what I need is that by clicking a button (or not), it is possible to get my location and automatically be informed of which point marked on the map is closest to me.

Someone can help me?

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {
      lat: 40.963308,
      lng: -8.594651
    }
  });

  // Create an array of alphabetical characters used to label the markers.
  var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

  // Add some markers to the map.
  // Note: The code uses the JavaScript Array.prototype.map() method to
  // create an array of markers based on a given "locations" array.
  // The map() method here has nothing to do with the Google Maps API.
  var markers = locations.map(function(location, i) {
    return new google.maps.Marker({
      position: location,
      label: labels[i % labels.length]
    });
  });

  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
  });
}

var locations = [{
    lat: 40.962157,
    lng: -8.593313
  },
  {
    lat: 40.962149,
    lng: -8.595695
  },
  {
    lat: 40.960351,
    lng: -8.598922
  },
  {
    lat: 40.967305,
    lng: -8.591450
  },
  {
    lat: 40.961682,
    lng: -8.608136
  }
]

  • But you want to show it on the map, or you just want to know the next?

  • Knowing the nearest is the most important, but if it is possible to show on the map would also be excellent!

1 answer

1

I made a logic so you can calculate the distance, and that way you can know which one is closer and even catch the latitude and longitude this to show on the map.

let atual = [-23.573037, -46.650190]
function calc(lat1, lon1, lat2, lon2){
        let R = 6371
	let dLat = (lat2 - lat1) * (Math.PI / 180)
	let dLon = (lon2 - lon1) * (Math.PI / 180)

	let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
	let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
	let d = R * c

	return d
}

function getGeo(position){
	alert('A distancia entre os prontos é de: ' + calc(position.coords.latitude, position.coords.longitude, atual[0], atual[1]))
}

function error() {
	alert("Erro")
}

let options = {
	enableHighAccuracy: true, 
	maximumAge        : 30000, 
	timeout           : 27000
}

let wpid = navigator.geolocation.watchPosition(getGeo, error, options)

Simply adapt as you see fit ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.