# google-maps - true - platform maps

## Google Maps Api v3-最も近いマーカーを見つける (4)

まず、イベントリスナーを追加する必要があります

``````google.maps.event.addListener(map, 'click', find_closest_marker);
``````

``````function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var R = 6371; // radius of earth in km
var distances = [];
var closest = -1;
for( i=0;i<map.markers.length; i++ ) {
var mlat = map.markers[i].position.lat();
var mlng = map.markers[i].position.lng();
var dLat  = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}

}
``````

マップオブジェクトに配列としてのマーカーがあります

``````function find_closest_marker( lat1, lon1 ) {
var pi = Math.PI;
var R = 6371; //equatorial radius
var distances = [];
var closest = -1;

for( i=0;i<markers.length; i++ ) {
var lat2 = markers[i].position.lat();
var lon2 = markers[i].position.lng();

var chLat = lat2-lat1;
var chLon = lon2-lon1;

var dLat = chLat*(pi/180);
var dLon = chLon*(pi/180);

var rLat1 = lat1*(pi/180);
var rLat2 = lat2*(pi/180);

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}

// (debug) The closest marker is:
console.log(markers[closest]);
}
``````