Yes. first you have to load the geometry library
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script><script>
Then you can use the Google maps function google.maps.geometry.spherical.computeDistanceBetween
You put the results in a for-loop, or in an array; then you return the minimal result.
Here is a web example of your question
<style>
#map {
height: 400px;
}
</style>
<div id="map"></div>
<input type="button" value="Minimal Distance" onclick="displayMinimalDistance()">
<div id="log"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script><script>
var myLocations = [
{lat: 50.0,lng: 4.5},
{lat: 50.1,lng: 4.7},
{lat: 50.4,lng: 4.8},
{lat: 50.7,lng: 4.9},
{lat: 50.2,lng: 4.4},
{lat: 50.5,lng: 4.0},
{lat: 50.8,lng: 4.6},
{lat: 50.3,lng: 4.1},
{lat: 50.6,lng: 4.2},
{lat: 50.9,lng: 4.3}
];
var myLocation = {lat: 50.5,lng: 4.5};
// Google maps stuff
function initialize() {
var markers = [];
var myMarker;
var mapCenter = new google.maps.LatLng(50.5, 4.5);
var myOptions = {
zoom: 8,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
addMarkers();
// adding the markers
function addMarkers() {
for(i in myLocations) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(myLocations[i].lat, myLocations[i].lng),
title: i,
map: map
})
);
}
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(myLocation.lat, myLocation.lng),
title: 'You are here',
icon: {
url: 'http://www.euroheat.co.uk/images/you-are-here-icon.png',
size: new google.maps.Size(48, 48),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(24,42)
},
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
// distance stuff
// returns an object: {i: 'key of the location', dist: 'distance'}
function getMinimalDistance(location, locations) {
var minDistance = 20000000; // and now we will look for any shorter distance
var minDistanceKey = -1;
var dist;
for(i in locations) {
dist = getDistance(location, locations[i]);
if(dist < minDistance) {
minDistance = dist;
minDistanceKey = i;
}
}
return {i: minDistanceKey, dist: minDistance};
}
function getDistance(source, destination) {
return google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(source.lat, source.lng),
new google.maps.LatLng(destination.lat, destination.lng)
);
}
// writes down the result of getMinimalDistance to a log div
function displayMinimalDistance() {
var minDistance = getMinimalDistance(myLocation, myLocations);
document.getElementById('log').innerHTML =
'Key of the marker at minimal distance: ' + minDistance.i
+ ' - distance: ' + minDistance.dist;
}
</script>