var map = $('#map');
// 模擬目前位置
var current = ['25.04151536540612', '121.56354904174805'];
var loc = [
{'addr': ['25.034516521123315','121.56496524810791'], 'text': '<strong>110台灣台北市信義區台北101</strong>'},
{'addr': ['25.037627167884715', '121.56732559204102'], 'text': '<strong>110台灣台北市信義區松壽路20巷</strong>'},
{'addr': ['25.039726809855434', '121.55633926391602'], 'text': '<strong>106台灣台北市大安區光復南路280巷25號</strong>'},
{'addr': ['25.037160575899154', '121.55350685119629'], 'text': '<strong>106台灣台北市大安區仁愛路四段300巷11號</strong>'},
{'addr': ['25.035877438787317', '121.55715465545654'], 'text': '<strong>106台灣台北市大安區光復南路440-1號</strong>'},
{'addr': ['25.033972149830436', '121.56063079833984'], 'text': '<strong>110台灣台北市信義區莊敬路</strong>'},
{'addr': ['25.031794640503858', '121.56414985656738'], 'text': '<strong>110台灣台北市信義區松勤街80號</strong>'},
{'addr': ['25.035255306871402', '121.56998634338379'], 'text': '<strong>110台灣台北市信義區松勇路47號</strong>'},
{'addr': ['25.033855498524844', '121.5686559677124'], 'text': '<strong>110台灣台北市信義區松仁路130號</strong>'},
//新增一標記為目前位置
{'addr': current, 'text': '<strong>目前位置</strong>', 'icon': 'http://app.essoduke.org/tinyMap/4.png', 'label': '目前位置', 'css': 'label'},
];
map.tinyMap({
'center': {
'x': '25.037627167884715',
'y': '121.56732559204102'
},
'zoom': 14,
'marker': loc,
'event': {
'idle': {
'func': function () {
var i = 0,
icon = {},
pos = {},
distance = [],
nearest = false,
// 取得目前位置的 LatLng 物件
now = new google.maps.LatLng(current[0], current[1]),
// 取得 instance
m = map.data('tinyMap'),
// 取得已建立的標記
markers = m._markers;
// 使用迴圈比對標記(忽略最末個)
for (i; i < loc.length - 1; i += 1) {
// 建立標記的 LatLng 物件
pos = new google.maps.LatLng(loc[i].addr[0], loc[i].addr[1]);
/**
* 利用幾何圖形庫比對標記與目前位置的測地線直線距離並存入陣列。
* http://goo.gl/ncP2Gz
*/ distance.push(google.maps.geometry.spherical.computeDistanceBetween(pos, now));
}
//console.dir(distance);
// 尋找陣列中最小值的索引值
nearest = distance.indexOf(Math.min.apply(Math, distance));
if (false !== nearest) {
if (undefined !== markers[nearest].infoWindow) {
// 開啟此標記的 infoWindow
markers[nearest].infoWindow.open(m.map, markers[nearest]);
// 更換此標記的圖示
markers[nearest].setIcon('http://app.essoduke.org/tinyMap/6.png');
markers[nearest].infoWindow.content += '<p>距離: ' + distance[nearest].toString() + ' 公尺</p>';
// 移動此標記至地圖中心
m.map.panTo(markers[nearest].position);
}
}
},
'once': true
}
}
});
<div id="map"></div>
<!-- 會使用到幾何計算功能,所以 Google Maps API 需額外引入 libraries=geometry -->
<!-- <script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script> -->
<div id="map"></div>
#map{width:100%;height:300px}
.label{padding:6px;color:white;background:rgba(0,0,0,0.6)}
External resources loaded into this fiddle: