tinyMap: find nearest marker

by essoduke chang

HTML

<script src="http://maps.google.com/maps/api/js?sensor=false&amp;language=zh-TW&amp;libraries=geometry"></script>
<script src="http://app.essoduke.org/tinyMap/jquery.tinyMap-2.8.5.min.js"></script>
<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>

CSS

#map{width:100%;height:300px}
.label{padding:6px;color:white;background:rgba(0,0,0,0.6)}

JavaScript

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 物件
   ...