/* 縮小失敗。正在傳回未縮小的內容。
(4,9): run-time error CSS1031: Expected selector, found '='
(4,9): run-time error CSS1025: Expected comma or open brace, found '='
(9,2): run-time error CSS1019: Unexpected token, found ')'
(13,23): run-time error CSS1031: Expected selector, found ';'
(13,23): run-time error CSS1025: Expected comma or open brace, found ';'
(15,13): run-time error CSS1031: Expected selector, found '='
(15,13): run-time error CSS1025: Expected comma or open brace, found '='
(18,2): run-time error CSS1019: Unexpected token, found ')'
(20,18): run-time error CSS1031: Expected selector, found '='
(20,18): run-time error CSS1025: Expected comma or open brace, found '='
(23,2): run-time error CSS1019: Unexpected token, found ')'
(24,13): run-time error CSS1031: Expected selector, found '='
(24,13): run-time error CSS1025: Expected comma or open brace, found '='
(27,2): run-time error CSS1019: Unexpected token, found ')'
(28,5): run-time error CSS1030: Expected identifier, found 'addLayer('
(28,5): run-time error CSS1031: Expected selector, found 'addLayer('
(28,5): run-time error CSS1025: Expected comma or open brace, found 'addLayer('
(29,20): run-time error CSS1031: Expected selector, found '='
(29,20): run-time error CSS1025: Expected comma or open brace, found '='
(31,10): run-time error CSS1031: Expected selector, found 'changeBaseMap('
(31,10): run-time error CSS1025: Expected comma or open brace, found 'changeBaseMap('
(53,1): run-time error CSS1019: Unexpected token, found '$'
(53,2): run-time error CSS1019: Unexpected token, found '('
(53,3): run-time error CSS1019: Unexpected token, found '"#zoomIn"'
(53,12): run-time error CSS1019: Unexpected token, found ')'
(53,14): run-time error CSS1030: Expected identifier, found 'click('
(53,14): run-time error CSS1019: Unexpected token, found 'click('
(53,29): run-time error CSS1031: Expected selector, found '('
(53,29): run-time error CSS1025: Expected comma or open brace, found '('
(55,2): run-time error CSS1019: Unexpected token, found ')'
(56,1): run-time error CSS1019: Unexpected token, found '$'
(56,2): run-time error CSS1019: Unexpected token, found '('
(56,3): run-time error CSS1019: Unexpected token, found '"#zoomOut"'
(56,13): run-time error CSS1019: Unexpected token, found ')'
(56,15): run-time error CSS1030: Expected identifier, found 'click('
(56,15): run-time error CSS1019: Unexpected token, found 'click('
(56,30): run-time error CSS1031: Expected selector, found '('
(56,30): run-time error CSS1025: Expected comma or open brace, found '('
(58,2): run-time error CSS1019: Unexpected token, found ')'
(62,14): run-time error CSS1031: Expected selector, found ';'
(62,14): run-time error CSS1025: Expected comma or open brace, found ';'
(63,1): run-time error CSS1019: Unexpected token, found '$'
(63,2): run-time error CSS1019: Unexpected token, found '('
(63,3): run-time error CSS1019: Unexpected token, found '"#loCate"'
(63,12): run-time error CSS1019: Unexpected token, found ')'
(63,14): run-time error CSS1030: Expected identifier, found 'click('
(63,14): run-time error CSS1019: Unexpected token, found 'click('
(63,29): run-time error CSS1031: Expected selector, found '('
(63,29): run-time error CSS1025: Expected comma or open brace, found '('
(77,2): run-time error CSS1019: Unexpected token, found ')'
(78,10): run-time error CSS1031: Expected selector, found 'showError('
(78,10): run-time error CSS1025: Expected comma or open brace, found 'showError('
(101,16): run-time error CSS1031: Expected selector, found '='
(101,16): run-time error CSS1025: Expected comma or open brace, found '='
(102,5): run-time error CSS1030: Expected identifier, found 'addControl('
(102,5): run-time error CSS1031: Expected selector, found 'addControl('
(102,5): run-time error CSS1025: Expected comma or open brace, found 'addControl('
(118,2): run-time error CSS1019: Unexpected token, found ')'
(118,3): run-time error CSS1019: Unexpected token, found ')'
(120,5): run-time error CSS1030: Expected identifier, found 'on('
(120,5): run-time error CSS1031: Expected selector, found 'on('
(120,5): run-time error CSS1025: Expected comma or open brace, found 'on('
(123,2): run-time error CSS1019: Unexpected token, found ')'
(131,18): run-time error CSS1031: Expected selector, found '='
(131,18): run-time error CSS1025: Expected comma or open brace, found '='
(132,14): run-time error CSS1031: Expected selector, found '='
(132,14): run-time error CSS1025: Expected comma or open brace, found '='
(133,14): run-time error CSS1031: Expected selector, found '='
(133,14): run-time error CSS1025: Expected comma or open brace, found '='
(135,9): run-time error CSS1030: Expected identifier, found 'log('
(135,9): run-time error CSS1031: Expected selector, found 'log('
(135,9): run-time error CSS1025: Expected comma or open brace, found 'log('
(136,18): run-time error CSS1031: Expected selector, found '='
(136,18): run-time error CSS1025: Expected comma or open brace, found '='
(137,17): run-time error CSS1031: Expected selector, found '='
(137,17): run-time error CSS1025: Expected comma or open brace, found '='
(138,17): run-time error CSS1031: Expected selector, found '='
(138,17): run-time error CSS1025: Expected comma or open brace, found '='
(141,12): run-time error CSS1031: Expected selector, found '='
(141,12): run-time error CSS1025: Expected comma or open brace, found '='
(142,12): run-time error CSS1031: Expected selector, found '='
(142,12): run-time error CSS1025: Expected comma or open brace, found '='
(143,14): run-time error CSS1030: Expected identifier, found '0'
(143,14): run-time error CSS1033: Expected closing bracket, found '0'
(143,15): run-time error CSS1031: Expected selector, found ']'
(143,15): run-time error CSS1025: Expected comma or open brace, found ']'
(145,14): run-time error CSS1030: Expected identifier, found '1'
(145,14): run-time error CSS1033: Expected closing bracket, found '1'
(145,15): run-time error CSS1031: Expected selector, found ']'
(145,15): run-time error CSS1025: Expected comma or open brace, found ']'
(147,8): run-time error CSS1031: Expected selector, found '('
(147,8): run-time error CSS1025: Expected comma or open brace, found '('
(175,1): run-time error CSS1019: Unexpected token, found '$'
(175,2): run-time error CSS1019: Unexpected token, found '('
(175,9): run-time error CSS1031: Expected selector, found ')'
(175,9): run-time error CSS1025: Expected comma or open brace, found ')'
(177,2): run-time error CSS1019: Unexpected token, found ')'
(179,15): run-time error CSS1031: Expected selector, found '='
(179,15): run-time error CSS1025: Expected comma or open brace, found '='
(196,11): run-time error CSS1030: Expected identifier, found 'singFun('
(196,11): run-time error CSS1031: Expected selector, found 'singFun('
(196,11): run-time error CSS1025: Expected comma or open brace, found 'singFun('
(198,15): run-time error CSS1031: Expected selector, found ';'
(198,15): run-time error CSS1025: Expected comma or open brace, found ';'
(199,16): run-time error CSS1031: Expected selector, found ';'
(199,16): run-time error CSS1025: Expected comma or open brace, found ';'
(201,10): run-time error CSS1031: Expected selector, found 'toggleSidebar('
(201,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSidebar('
(222,1): run-time error CSS1019: Unexpected token, found '$'
(222,2): run-time error CSS1019: Unexpected token, found '('
(222,11): run-time error CSS1031: Expected selector, found ')'
(222,11): run-time error CSS1025: Expected comma or open brace, found ')'
(232,2): run-time error CSS1019: Unexpected token, found ')'
(236,14): run-time error CSS1031: Expected selector, found '='
(236,14): run-time error CSS1025: Expected comma or open brace, found '='
(317,10): run-time error CSS1031: Expected selector, found 'setResultbarListWindows('
(317,10): run-time error CSS1025: Expected comma or open brace, found 'setResultbarListWindows('
(334,10): run-time error CSS1031: Expected selector, found '='
(334,10): run-time error CSS1025: Expected comma or open brace, found '='
(335,10): run-time error CSS1031: Expected selector, found '='
(335,10): run-time error CSS1025: Expected comma or open brace, found '='
(336,11): run-time error CSS1031: Expected selector, found '='
(336,11): run-time error CSS1025: Expected comma or open brace, found '='
(337,10): run-time error CSS1031: Expected selector, found '='
(337,10): run-time error CSS1025: Expected comma or open brace, found '='
(338,10): run-time error CSS1031: Expected selector, found '='
(338,10): run-time error CSS1025: Expected comma or open brace, found '='
(339,11): run-time error CSS1031: Expected selector, found '='
(339,11): run-time error CSS1025: Expected comma or open brace, found '='
(340,8): run-time error CSS1031: Expected selector, found '='
(340,8): run-time error CSS1025: Expected comma or open brace, found '='
(341,10): run-time error CSS1031: Expected selector, found '='
(341,10): run-time error CSS1025: Expected comma or open brace, found '='
(342,11): run-time error CSS1031: Expected selector, found '='
(342,11): run-time error CSS1025: Expected comma or open brace, found '='
(343,13): run-time error CSS1031: Expected selector, found '='
(343,13): run-time error CSS1025: Expected comma or open brace, found '='
(345,10): run-time error CSS1031: Expected selector, found '='
(345,10): run-time error CSS1025: Expected comma or open brace, found '='
(346,10): run-time error CSS1031: Expected selector, found '='
(346,10): run-time error CSS1025: Expected comma or open brace, found '='
(347,10): run-time error CSS1031: Expected selector, found '='
(347,10): run-time error CSS1025: Expected comma or open brace, found '='
(348,14): run-time error CSS1031: Expected selector, found '='
(348,14): run-time error CSS1025: Expected comma or open brace, found '='
(349,14): run-time error CSS1031: Expected selector, found '='
(349,14): run-time error CSS1025: Expected comma or open brace, found '='
(350,14): run-time error CSS1031: Expected selector, found '='
(350,14): run-time error CSS1025: Expected comma or open brace, found '='
(351,16): run-time error CSS1031: Expected selector, found '='
(351,16): run-time error CSS1025: Expected comma or open brace, found '='
(352,16): run-time error CSS1031: Expected selector, found '='
(352,16): run-time error CSS1025: Expected comma or open brace, found '='
(353,16): run-time error CSS1031: Expected selector, found '='
(353,16): run-time error CSS1025: Expected comma or open brace, found '='
(354,9): run-time error CSS1031: Expected selector, found '='
(354,9): run-time error CSS1025: Expected comma or open brace, found '='
(356,10): run-time error CSS1031: Expected selector, found 'LatLon2UTM('
(356,10): run-time error CSS1025: Expected comma or open brace, found 'LatLon2UTM('
(433,10): run-time error CSS1031: Expected selector, found 'UTM2LatLon('
(433,10): run-time error CSS1025: Expected comma or open brace, found 'UTM2LatLon('
(513,10): run-time error CSS1031: Expected selector, found 'twd97_to_latlng('
(513,10): run-time error CSS1025: Expected comma or open brace, found 'twd97_to_latlng('
(564,1): run-time error CSS1019: Unexpected token, found '$'
(564,2): run-time error CSS1019: Unexpected token, found '('
(564,11): run-time error CSS1031: Expected selector, found ')'
(564,11): run-time error CSS1025: Expected comma or open brace, found ')'
(571,2): run-time error CSS1019: Unexpected token, found ')'
(575,10): run-time error CSS1031: Expected selector, found 'townItemhtml('
(575,10): run-time error CSS1025: Expected comma or open brace, found 'townItemhtml('
(579,20): run-time error CSS1031: Expected selector, found '='
(579,20): run-time error CSS1025: Expected comma or open brace, found '='
(580,1): run-time error CSS1019: Unexpected token, found '$'
(580,2): run-time error CSS1019: Unexpected token, found '('
(580,11): run-time error CSS1031: Expected selector, found ')'
(580,11): run-time error CSS1025: Expected comma or open brace, found ')'
(632,2): run-time error CSS1019: Unexpected token, found ')'
(633,18): run-time error CSS1031: Expected selector, found '='
(633,18): run-time error CSS1025: Expected comma or open brace, found '='
(634,1): run-time error CSS1019: Unexpected token, found '$'
(634,2): run-time error CSS1019: Unexpected token, found '('
(634,11): run-time error CSS1031: Expected selector, found ')'
(634,11): run-time error CSS1025: Expected comma or open brace, found ')'
(673,2): run-time error CSS1019: Unexpected token, found ')'
(676,1): run-time error CSS1019: Unexpected token, found '$'
(676,2): run-time error CSS1019: Unexpected token, found '('
(676,11): run-time error CSS1031: Expected selector, found ')'
(676,11): run-time error CSS1025: Expected comma or open brace, found ')'
(688,2): run-time error CSS1019: Unexpected token, found ')'
(689,1): run-time error CSS1019: Unexpected token, found '$'
(689,2): run-time error CSS1019: Unexpected token, found '('
(689,11): run-time error CSS1031: Expected selector, found ')'
(689,11): run-time error CSS1025: Expected comma or open brace, found ')'
(701,2): run-time error CSS1019: Unexpected token, found ')'
(702,1): run-time error CSS1019: Unexpected token, found '$'
(702,2): run-time error CSS1019: Unexpected token, found '('
(702,11): run-time error CSS1031: Expected selector, found ')'
(702,11): run-time error CSS1025: Expected comma or open brace, found ')'
(714,2): run-time error CSS1019: Unexpected token, found ')'
(716,1): run-time error CSS1019: Unexpected token, found '$'
(716,2): run-time error CSS1019: Unexpected token, found '('
(716,11): run-time error CSS1031: Expected selector, found ')'
(716,11): run-time error CSS1025: Expected comma or open brace, found ')'
(726,2): run-time error CSS1019: Unexpected token, found ')'
(731,1): run-time error CSS1019: Unexpected token, found '$'
(731,2): run-time error CSS1019: Unexpected token, found '('
(731,11): run-time error CSS1031: Expected selector, found ')'
(731,11): run-time error CSS1025: Expected comma or open brace, found ')'
(743,2): run-time error CSS1019: Unexpected token, found ')'
(750,22): run-time error CSS1031: Expected selector, found '='
(750,22): run-time error CSS1025: Expected comma or open brace, found '='
(751,22): run-time error CSS1031: Expected selector, found '='
(751,22): run-time error CSS1025: Expected comma or open brace, found '='
(752,17): run-time error CSS1031: Expected selector, found '='
(752,17): run-time error CSS1025: Expected comma or open brace, found '='
(753,17): run-time error CSS1031: Expected selector, found '='
(753,17): run-time error CSS1025: Expected comma or open brace, found '='
(756,17): run-time error CSS1031: Expected selector, found '='
(756,17): run-time error CSS1025: Expected comma or open brace, found '='
(757,14): run-time error CSS1031: Expected selector, found ';'
(757,14): run-time error CSS1025: Expected comma or open brace, found ';'
(761,20): run-time error CSS1031: Expected selector, found '='
(761,20): run-time error CSS1025: Expected comma or open brace, found '='
(764,2): run-time error CSS1019: Unexpected token, found ')'
(765,18): run-time error CSS1031: Expected selector, found '='
(765,18): run-time error CSS1025: Expected comma or open brace, found '='
(768,2): run-time error CSS1019: Unexpected token, found ')'
(769,18): run-time error CSS1031: Expected selector, found '='
(769,18): run-time error CSS1025: Expected comma or open brace, found '='
(772,2): run-time error CSS1019: Unexpected token, found ')'
(773,18): run-time error CSS1031: Expected selector, found '='
(773,18): run-time error CSS1025: Expected comma or open brace, found '='
(776,2): run-time error CSS1019: Unexpected token, found ')'
(777,11): run-time error CSS1031: Expected selector, found '='
(777,11): run-time error CSS1025: Expected comma or open brace, found '='
(780,2): run-time error CSS1019: Unexpected token, found ')'
(781,18): run-time error CSS1031: Expected selector, found '='
(781,18): run-time error CSS1025: Expected comma or open brace, found '='
(784,2): run-time error CSS1019: Unexpected token, found ')'
(785,18): run-time error CSS1031: Expected selector, found '='
(785,18): run-time error CSS1025: Expected comma or open brace, found '='
(788,2): run-time error CSS1019: Unexpected token, found ')'
(791,28): run-time error CSS1031: Expected selector, found '='
(791,28): run-time error CSS1025: Expected comma or open brace, found '='
(797,2): run-time error CSS1019: Unexpected token, found ')'
(798,30): run-time error CSS1031: Expected selector, found '='
(798,30): run-time error CSS1025: Expected comma or open brace, found '='
(804,2): run-time error CSS1019: Unexpected token, found ')'
(805,30): run-time error CSS1031: Expected selector, found '='
(805,30): run-time error CSS1025: Expected comma or open brace, found '='
(811,2): run-time error CSS1019: Unexpected token, found ')'
(812,30): run-time error CSS1031: Expected selector, found '='
(812,30): run-time error CSS1025: Expected comma or open brace, found '='
(818,2): run-time error CSS1019: Unexpected token, found ')'
(819,23): run-time error CSS1031: Expected selector, found '='
(819,23): run-time error CSS1025: Expected comma or open brace, found '='
(825,2): run-time error CSS1019: Unexpected token, found ')'
(826,30): run-time error CSS1031: Expected selector, found '='
(826,30): run-time error CSS1025: Expected comma or open brace, found '='
(832,2): run-time error CSS1019: Unexpected token, found ')'
(833,30): run-time error CSS1031: Expected selector, found '='
(833,30): run-time error CSS1025: Expected comma or open brace, found '='
(839,2): run-time error CSS1019: Unexpected token, found ')'
(843,1): run-time error CSS1019: Unexpected token, found '$'
(843,2): run-time error CSS1019: Unexpected token, found '('
(843,11): run-time error CSS1031: Expected selector, found ')'
(843,11): run-time error CSS1025: Expected comma or open brace, found ')'
(936,2): run-time error CSS1019: Unexpected token, found ')'
(942,1): run-time error CSS1019: Unexpected token, found '$'
(942,2): run-time error CSS1019: Unexpected token, found '('
(942,11): run-time error CSS1031: Expected selector, found ')'
(942,11): run-time error CSS1025: Expected comma or open brace, found ')'
(954,2): run-time error CSS1019: Unexpected token, found ')'
(956,10): run-time error CSS1031: Expected selector, found 'clearResultList('
(956,10): run-time error CSS1025: Expected comma or open brace, found 'clearResultList('
(963,10): run-time error CSS1031: Expected selector, found 'hideResultbar('
(963,10): run-time error CSS1025: Expected comma or open brace, found 'hideResultbar('
(970,10): run-time error CSS1031: Expected selector, found 'clearAreaLayer('
(970,10): run-time error CSS1025: Expected comma or open brace, found 'clearAreaLayer('
(979,10): run-time error CSS1031: Expected selector, found 'clearQueryLayer('
(979,10): run-time error CSS1025: Expected comma or open brace, found 'clearQueryLayer('
(1002,1): run-time error CSS1019: Unexpected token, found '$'
(1002,2): run-time error CSS1019: Unexpected token, found '('
(1002,3): run-time error CSS1019: Unexpected token, found '"#testbtn"'
(1002,13): run-time error CSS1019: Unexpected token, found ')'
(1002,15): run-time error CSS1030: Expected identifier, found 'click('
(1002,15): run-time error CSS1019: Unexpected token, found 'click('
(1002,30): run-time error CSS1031: Expected selector, found '('
(1002,30): run-time error CSS1025: Expected comma or open brace, found '('
(1009,2): run-time error CSS1019: Unexpected token, found ')'
(1012,14): run-time error CSS1031: Expected selector, found '='
(1012,14): run-time error CSS1025: Expected comma or open brace, found '='
(1013,10): run-time error CSS1031: Expected selector, found 'getRestaurants('
(1013,10): run-time error CSS1025: Expected comma or open brace, found 'getRestaurants('
(1145,10): run-time error CSS1031: Expected selector, found 'getRestaurantDetail('
(1145,10): run-time error CSS1025: Expected comma or open brace, found 'getRestaurantDetail('
(1196,24): run-time error CSS1031: Expected selector, found '='
(1196,24): run-time error CSS1025: Expected comma or open brace, found '='
(1197,10): run-time error CSS1031: Expected selector, found 'getBadgeHotels('
(1197,10): run-time error CSS1025: Expected comma or open brace, found 'getBadgeHotels('
(1328,10): run-time error CSS1031: Expected selector, found 'getBadgeHotelDetail('
(1328,10): run-time error CSS1025: Expected comma or open brace, found 'getBadgeHotelDetail('
(1368,22): run-time error CSS1031: Expected selector, found '='
(1368,22): run-time error CSS1025: Expected comma or open brace, found '='
(1369,10): run-time error CSS1031: Expected selector, found 'getEcoHotels('
(1369,10): run-time error CSS1025: Expected comma or open brace, found 'getEcoHotels('
(1496,10): run-time error CSS1031: Expected selector, found 'getEcoHotelDetail('
(1496,10): run-time error CSS1025: Expected comma or open brace, found 'getEcoHotelDetail('
(1551,19): run-time error CSS1031: Expected selector, found '='
(1551,19): run-time error CSS1025: Expected comma or open brace, found '='
(1552,10): run-time error CSS1031: Expected selector, found 'getStores('
(1552,10): run-time error CSS1025: Expected comma or open brace, found 'getStores('
(1692,10): run-time error CSS1031: Expected selector, found 'getStoreDetail('
(1692,10): run-time error CSS1025: Expected comma or open brace, found 'getStoreDetail('
(1735,10): run-time error CSS1031: Expected selector, found 'getStoreGoods('
(1735,10): run-time error CSS1025: Expected comma or open brace, found 'getStoreGoods('
(1769,10): run-time error CSS1031: Expected selector, found 'setLocation('
(1769,10): run-time error CSS1025: Expected comma or open brace, found 'setLocation('
(1779,10): run-time error CSS1031: Expected selector, found 'removePulsing('
(1779,10): run-time error CSS1025: Expected comma or open brace, found 'removePulsing('
(1803,10): run-time error CSS1031: Expected selector, found 'getPlushIconU('
(1803,10): run-time error CSS1025: Expected comma or open brace, found 'getPlushIconU('
 */
/// <summary> 地圖初始化 </summary>
//function MapInit(mapId) {
// #region 創建地圖
var map = L.map('map', {
//var map = L.map('map', {
    center: [25.2, 121.5],
    zoom: 13,
    zoomControl: false
});
// #endregion 創建地圖

// #region 加入底圖
var beforeBaseMapLayer;
//var TGOSMAP = L.tileLayer('https://gis.sinica.edu.tw/tgos/file-exists.php?img=TGOSMAP_W-png-{z}-{x}-{y}', {
var TGOSMAP = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'TGOS電子地圖'
});
//beforeBaseMapLayer = TGOSMAP;
var TGOS_F2IMAGE = L.tileLayer('https://wmts.nlsc.gov.tw/wmts/PHOTO2/Default/GoogleMapsCompatible/{z}/{y}/{x}', {
    maxZoom: 17,
    attribution: '福衛二號影像'
});
var ROADMAP = L.tileLayer('https://wmts.nlsc.gov.tw/wmts/PHOTO_MIX/Default/GoogleMapsCompatible/{z}/{y}/{x}', {
    maxZoom: 17,
    attribution: '福衛二號混合圖'
});
map.addLayer(TGOSMAP);
beforeBaseMapLayer = TGOSMAP;
//_GISLayout: 底圖切換
function changeBaseMap(name) {
    map.removeLayer(beforeBaseMapLayer);
    switch(name) {
        case "福衛二號影像":
            beforeBaseMapLayer = TGOS_F2IMAGE;
            map.addLayer(TGOS_F2IMAGE);

            break;
        case "通用電子地圖":
            beforeBaseMapLayer = TGOSMAP;
            map.addLayer(TGOSMAP);
            break;
        case "福衛二號混合圖":
            beforeBaseMapLayer = ROADMAP;
            map.addLayer(ROADMAP);
            break;
    }
    $("#mapSelected").html('<i class="fa fa-map-o"></i><span> ' + name +'</span> ');
}
// #endregion 加入底圖

// #region 地圖縮放
$("#zoomIn").click(function () {
    map.setZoom(map.getZoom() + 1);
});
$("#zoomOut").click(function () {
    map.setZoom(map.getZoom() - 1);
});
// #endregion 地圖縮放

// #region 即時定位
var gpsMarker;
$("#loCate").click(function () {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
           
            if (gpsMarker !== undefined) {
                map.removeLayer(gpsMarker);
            }
            gpsMarker = L.marker([position.coords.latitude, position.coords.longitude]
            ).addTo(map);
            map.setView([position.coords.latitude, position.coords.longitude]);
        }, showError);
    } else {
        x.innerHTML = "Geolocation is not supported";
    }
});
function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            //x.innerHTML = "User denied the request for Geolocation."
            alert("用戶不允許地理位置定位");
            break;
        case error.POSITION_UNAVAILABLE:
            //x.innerHTML = "Location information is unavailable."
            alert("無法獲取當前位置");
            break;
        case error.TIMEOUT:
            //x.innerHTML = "The request to get user location timed out."
            alert("操作超時");
            break;
        case error.UNKNOWN_ERROR:
            //x.innerHTML = "An unknown error occurred."
            alert("未知錯誤");
            break;
    }
}
// #endregion 即時定位

// #region 繪圖測量
var drawnItems = L.featureGroup().addTo(map);
map.addControl(new L.Control.Draw({
    position: 'topright',
    edit: {
        edit: false,
        featureGroup: drawnItems,
        poly: { allowIntersection: false },

    },
    draw: {
        marker: false,
        circlemarker: false,
        polygon: {
            allowIntersection: false,
            showArea: true
        }
    }
}));

map.on(L.Draw.Event.CREATED, function (event) {
    var layer = event.layer;
    drawnItems.addLayer(layer);
});
// #endregion 繪圖測量   // return map;

//}

// #region 網域判斷

var MapServerUrl = new Array();
var hostname = window.location.hostname;
var protocol = window.location.protocol;

console.log(protocol);
var testHostname = 'localhost';
var eriHostname = 'greenlifestyle.eri.com.tw';
var epaHostname = 'greenlifestyle.moenv.gov.tw';

//ApiServerUrl
var eriApi = '//greenliving.eri.com.tw/PublicRwd/';//greenliving.eri.com.tw/PublicRwd/
var epaApi = '//greenliving.moenv.gov.tw/newPublic/';
MapServerUrl[0] = 'http://localhost:62334/Home/';
//MapServerUrl[1] = epaApi;
MapServerUrl[1] = eriApi;
//Access-Control-Allow-Origin: *
switch (hostname) {
    case eriHostname:
        MapServerUrl[0] = protocol +"//greenlifestyle.eri.com.tw/GIS/";
        //MapServerUrl[1] = protocol + eriApi;
        MapServerUrl[1] = protocol + eriApi;
        break;
    case epaHostname:
        MapServerUrl[0] = protocol +"//greenlifestyle.moenv.gov.tw/GIS/";
        MapServerUrl[1] = protocol+epaApi;
        break;
    case testHostname:
        MapServerUrl[0] = 'http://localhost:62334/';
        MapServerUrl[1] = protocol + eriApi; //eriApi
      
        break;
    default:
        MapServerUrl[0] = window.location.href;
        MapServerUrl[1] = protocol + eriApi;
        break;

}
// #endregion 網域判斷
//$(document).ajaxStart(function () {
//    $.LoadingOverlay("show");
//});
//$(document).ajaxStop(function () {
//    $.LoadingOverlay("hide");
//});
$(window).resize(function () {
    setResultbarListWindows();
});
//#region 導覽列 nav 切換
var navToggle = {
    //單一功能
    singFun: function () {
        $("#btn-nav").click(function () {
            $("#sidebar").toggle("drop");
            $('#resultbar_list').hide();
            $('.resultbar').hide();
        });

    },
    //多個功能
    multipleFun: function () {
        $("#btn-nav").click(function () {
            $("div.nav").toggle("blind");
        });
    }
};
navToggle.singFun();
// 功能視窗切換
var preSidebar;
var thisSidebar;

function toggleSidebar(tag) {
    
    //console.log($(tag).hasClass('resultClose'));
    thisSidebar = $(tag);
    var isResultbar = $(tag).hasClass('resultClose');
    if (!isResultbar) {
        //$("#navbar").toggle("blind");
        if (preSidebar) {
            preSidebar.hide();
            //alert('presidebar');
        }

        preSidebar = $(thisSidebar).parents('.resultbar');
    }
    $(thisSidebar).parents('.resultbar').toggle(500);
    var isResultbar_list = thisSidebar.parent().parent().prop('id') === 'resultbar_list';
    if (isResultbar_list) {
        $('#listBtn').show();
    }
}

$(document).on('click', '#listBtn', function () {

    $('#resultbar_list').toggle( function () {
        if ($('#resultbar_list').is(':visible')) {
            $('.resultbar[id !="resultbar_list"]:visible').hide();
        }
    });
    $('#sidebar').hide();
   
   
});
//#endregion 導覽列 nav 切換


var AjaxCall = function (func, dat, callback) {
    /// <summary>
    /// 資料查詢呼叫
    /// </summary>
    /// <param name="_func">呼叫方法</param>
    /// <param name="_dat">傳送資料</param>
    /// <param name="_callback">回傳成功處理函式.</param>
    /// <param name="_blockUI">是否做BlockUI.</param>
    /// <returns></returns>
    var me = this;
    //if (typeof $.LoadingOverlay !== 'undefined') {
    //    $.LoadingOverlay("show");
    //}


    var ajax_type = "POST";
    var ajax_url = "";
    var ajax_async = true;
    var ajax_contentType = "application/json; charset=utf-8";
    var ajax_dataType = "json";
    var ajax_data = JSON.stringify(dat);
    var crossDomain = false;
    //console.log('MapServerUrl[0]');
    //console.log(dat);
    switch (func) {
        //取得行政區
        case "GetCountyGeo":
           // console.log('GetCountyGeodat.c');
            //console.log(dat.c);
            ajax_url = MapServerUrl[0] + "Home/GetCountyGeo?c=" + dat.c.value;
            break;
        case "GetTownList":
            ajax_url = MapServerUrl[0] +"Home/GetTownList?county=" + dat.county;
            break;
        case "GetTownGeo":
            ajax_url = MapServerUrl[0] +"Home/GetTownGeo?t=" + dat.t;
            break;
        default:
            //ajax_url = me.ServiceUrl + func;
            break;
    }

    $.ajax({
        type: ajax_type,
        url: ajax_url,
        contentType: ajax_contentType,
        crossDomain: crossDomain,
        //async: true,//若需要使用ajax取得的result的數值，必須設定為false(才會變成sync同步執行）
        async: ajax_async,//若需要使用ajax取得的result的數值，必須設定為false(才會變成sync同步執行）
        cache: false,
        dataType: ajax_dataType,
        data: ajax_data,
        success: function (data) {

            const result = data.hasOwnProperty('d') ? data.d : data;
            if (!result) {
                cosole.log("回傳成功但出錯:" + data);
                window.alertify.notify(`服務呼叫異常..(${func})`, "error", 2);
                return;
            }
            if (callback) callback(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log("XMLHttpRequest.status:" + XMLHttpRequest.status);
            console.log("XMLHttpRequest.readyState:" + XMLHttpRequest.readyState);
            console.log("textStatus:" + XMLHttpRequest.responseText);
            console.log("errorThrown:" + errorThrown);
            //window.alertify.notify(`服務呼叫異常..(${func})`, "error", 2);
        },
        complete: function (result) {
            console.log(result);
            //alert(typeof $.LoadingOverlay);//wenny:測試查詢中
            //if (typeof $.LoadingOverlay !== 'undefined') {
            //    $.LoadingOverlay("hide");
            //}
        }
    });
    return this;
}

function setResultbarListWindows(){
    var widowsW = $(window).width() - 232;
    var widowsH = $(window).height();
    var resultListW = $("#resultbar_list").width();
    var resultbarW = $("#resultbar_restaurant ").width();
   
    sd = $('.resultbar[id !="resultbar_list"]').is(':visible');
    //sd = $("#resultbar_restaurant").is(':visible');
    sq = $("#sidebar").is(':visible');

    if (!sq && sd) {
        $("#resultbar_list").show();
    }
    if (widowsW < (resultListW + resultbarW) && sd) {
        $("#resultbar_list").hide();
    } 
}
var A1_84=6378137.0;
var B1_84=6356752.3141;
var e2_84 = 0.0066943800355;
var A1_67=6378160.0;
var B1_67=6356774.7192;
var e2_67 = 0.006694541853;
var SK = new Array( 0.9999, 1.0, 0.9996 );
var Cent = new Array( 121.0, 121.0, 123.0 );
var Shift = new Array( 250000.0, 350000.0, 500000.0) ;
var DegreePI=180.0/Math.PI;

var XM84 = -3033819.548;
var YM84 =  5071301.969;
var ZM84 =  2391982.060;
var DeltaX84 = 754.812;
var DeltaY84 = 362.233;
var DeltaZ84 = 187.197;
var EpsilonX84 = -5.216/3600.0/DegreePI;
var EpsilonY84 = -8.846/3600.0/DegreePI;
var EpsilonZ84 = 35.781/3600.0/DegreePI;
var S84 = 3.161E-6;

function LatLon2UTM(Lon, Lat, AreaCode, Flag)
{
	var E1, E2, PH2, LM2, PH1, LM1, Temp1, Temp2, Temp3, Temp4;
	var Temp5, Temp6, Temp7;
	var RAP, UU, N, T;
	var A, B, C, D, E, PM, PH;
    var A1, B1;

    if( Flag == 0 )
    {
        A1 = A1_84;
        B1 = B1_84;
    }
    else
    {
        A1 = A1_67;
        B1 = B1_67;
    }

    E1 = 1.0-(B1/A1)*(B1/A1);
    E2 = (A1/B1)*(A1/B1)-1.0;

    PH2 = Lat/DegreePI;
    LM2 = Lon/DegreePI;
    LM1 = Cent[AreaCode]/DegreePI;
    PH1 = 0.0;

    Temp1 = Math.sin(PH2);
    Temp2 = Math.cos(PH2);
    RAP = LM2 - LM1;
    UU = E2 * Temp2*Temp2;
    Temp3 = 1.0 - E1 * Temp1*Temp1;
    N = A1/Math.sqrt(Temp3);
    T = Temp1/Temp2;
    Temp4 = N * Temp2 *RAP;
    Temp5 = N * (1.0 - T*T + UU)*Math.pow(Temp2, 3.0)*Math.pow(RAP,3.0)/6.0;
    Temp6 = 5.0 - 18.0*Math.pow(T,2.0)+Math.pow(T,4.0)+14.0*UU -
            58.0*UU*T*T;
    Temp7 = N * Temp6 * Math.pow( Temp2, 5.0) * Math.pow( RAP, 5.0) / 120.0;

    LM2 = Temp4 + Temp5 + Temp7;
    LM2 = SK[AreaCode] * LM2 + Shift[AreaCode];

    Temp4 = Math.pow( E1, 2.0 );
    Temp5 = Math.pow( E1, 3.0 );
    Temp6 = Math.pow( E1, 4.0 );
    A = 1.0 + 0.75*E1 + 45.0*Temp4/64.0 + 175.0*Temp5/256.0 +
        11025.0*Temp6/16384.0;
    B = 0.75*E1 + 15.0*Temp4/16.0 +525.0*Temp5/512.0 +
        2205.0*Temp6/2048.0;
    C = 15.0*Temp4/64.0 + 105.0*Temp5/256.0 + 2205.0*Temp6/4096.0;
    D = 35.0*Temp5/512.0 + 315.0*Temp6/2048.0;
    E = 315.0*Temp6/16384.0;

    Temp4 = A*(PH2-PH1) - B*(Math.sin(2.0*PH2) - Math.sin(2.0*PH1))/2.0;
    Temp5 = C*(Math.sin(4.0*PH2)-Math.sin(4.0*PH1));
    Temp6 = D*(Math.sin(6.0*PH2)-Math.sin(6.0*PH1));
    Temp7 = E*(Math.sin(8.0*PH2)-Math.sin(8.0*PH1));

    PM = A1*(1.0-E1)*(Temp4 + (Temp5/4.0) + (Temp6/6.0) + (Temp7/8.0));

    Temp4 = N*T*Math.pow(RAP, 2.0)*Math.pow(Temp2, 2.0)/2.0;
    Temp5 = 5.0 - Math.pow(T,2.0) + 9.0*UU + 4.0*Math.pow(UU,2.0);
    Temp6 = Math.pow(Temp2,4.0)*Math.pow(RAP,4.0)/24.0;
    Temp7 = 61.0 - 58.0*T*T + Math.pow(T,4.0) + 270.0*UU - 330.0*UU*T*T;

    PH = PM + Temp4 + N*T*Temp5*Temp6 +
    	 N*T*Math.pow(PH2,6.0)*Math.pow(RAP,6.0)*Temp7/720.0;

    PH2 = SK[AreaCode]*PH;
   
    //var pt = new Array(1);
    //pt[0]=LM2;
    //pt[1]=PH2;
    return { x: LM2, y: PH2 };
}

function UTM2LatLon(X,  Y, AreaCode, Flag)
{
	var N,E1,CN,CE,PH2,PH1,DS,RM,DPH;
	var Temp1,Temp2,Temp3,T,R,UU;
	var LM2, S, A1, B1;
	var i,IPAT;

    if( Flag == 0 )
    {
        A1 = A1_84;
        B1 = B1_84;
    }
    else
    {
        A1 = A1_67;
        B1 = B1_67;
    }

	E1 = 1.0 -(B1/A1) * (B1/A1);
	CN = Y;
	CE = X;
	CN /= SK[AreaCode];
	CE = (CE - Shift[AreaCode]) / SK[AreaCode];
	PH2 = 0.0;
	IPAT = 1200;
	DS = CN / IPAT;

	for ( i = 1; i <= IPAT; i++ )
	{
		Temp1 = Math.pow(Math.sin(PH2),2.0);
		Temp2 = 1.0 - E1 * Temp1;
		Temp3 = Math.pow(Temp2,1.5);
		RM = A1 * (1.0 - E1) / Temp3;
		DPH = DS / (2.0 * RM);
		PH1 = PH2 + DPH;
		Temp1 = Math.pow(Math.sin(PH1),2.0);
		Temp2 = 1.0 - E1 * Temp1;
		Temp3 = Math.pow(Temp2,1.5);
		RM = A1 * (1.0 - E1) / Temp3;
		DPH = DS / RM;
		PH2 = PH2 + DPH;
	}

	T = Math.sin(PH2) / Math.cos(PH2);
	Temp1 = Math.pow(Math.sin(PH2),2.0);
	Temp2 = 1.0 - E1 * Temp1;
	Temp3 = Math.pow(Temp2,1.5);
	R = A1 * (1.0 - E1) / Temp3;
	Temp3 = Math.pow(Temp2,0.5);
	N = A1 / Temp3;
	UU = N / R;
	S = 1.0 / Math.cos(PH2);
	Temp1 = T * Math.pow(CE,2.0) / (2.0 * R * N);
	Temp2 = T * Math.pow(CE,4.0) * ((-4.0 * Math.pow(UU,2.0)) +
			(9.0 * (1.0 - T*T)) + (12.0 * T * T)) /
			(24.0 * R * Math.pow(N,3.0));
	Temp3 = T * Math.pow(CE,6.0) * ((8.0 * Math.pow(UU,4.0) * (11.0 - 24.0 *T*T)) -
			(12.0 * Math.pow(UU,3.0) * (21.0 - 71.0 * T*T)) +
			(15.0 * Math.pow(UU,2.0) * (15.0 - (98.0 * T*T) + (15.0 * Math.pow(T,4)))) +
			(180.0 * UU * (5.0 * T*T -3.0 * Math.pow(T,4.0))) +
			(360.0 * Math.pow(T,4.0))) / (720. * R * Math.pow(N,5.0));
	PH2 = PH2 - Temp1 + Temp2 - Temp3;

	var Lat = PH2 * DegreePI;

    Temp1 = S*CE/N;
    Temp2 = S*Math.pow(CE,3.0)*(UU+2.0*T*T)/(6*Math.pow(N,3.0));
    Temp3 = S*Math.pow(CE,5.0)*((-4.0*Math.pow(UU,3.0)*(1.0-6.0*T*T))+
    		(UU*UU*(9.0-68.0*T*T)) + (72.0*UU*T*T) +
            (24.0*Math.pow(T,4.0)))/(120.0*Math.pow(N,5.0));
    LM2 = Temp1 - Temp2 + Temp3;
    var Lon = 121 + LM2*DegreePI;

    //var pt = new Array(1);
	
    //pt[0]=Lat;
    //pt[1]=Lon;
    return { x: Lon, y: Lat };
}

function twd97_to_latlng($x, $y, $z) {
    var pow = Math.pow, M_PI = Math.PI;
    var sin = Math.sin, cos = Math.cos, tan = Math.tan;
    var $a = 6378137.0, $b = 6356752.314245;
    var $lng0 = $z * M_PI / 180, $k0 = 0.9999, $dx = 250000, $dy = 0;
    var $e = pow((1 - pow($b, 2) / pow($a, 2)), 0.5);

    $x -= $dx;
    $y -= $dy;

    var $M = $y / $k0;

    var $mu = $M / ($a * (1.0 - pow($e, 2) / 4.0 - 3 * pow($e, 4) / 64.0 - 5 * pow($e, 6) / 256.0));
    var $e1 = (1.0 - pow((1.0 - pow($e, 2)), 0.5)) / (1.0 + pow((1.0 - pow($e, 2)), 0.5));

    var $J1 = (3 * $e1 / 2 - 27 * pow($e1, 3) / 32.0);
    var $J2 = (21 * pow($e1, 2) / 16 - 55 * pow($e1, 4) / 32.0);
    var $J3 = (151 * pow($e1, 3) / 96.0);
    var $J4 = (1097 * pow($e1, 4) / 512.0);

    var $fp = $mu + $J1 * sin(2 * $mu) + $J2 * sin(4 * $mu) + $J3 * sin(6 * $mu) + $J4 * sin(8 * $mu);

    var $e2 = pow(($e * $a / $b), 2);
    var $C1 = pow($e2 * cos($fp), 2);
    var $T1 = pow(tan($fp), 2);
    var $R1 = $a * (1 - pow($e, 2)) / pow((1 - pow($e, 2) * pow(sin($fp), 2)), (3.0 / 2.0));
    var $N1 = $a / pow((1 - pow($e, 2) * pow(sin($fp), 2)), 0.5);

    var $D = $x / ($N1 * $k0);

    var $Q1 = $N1 * tan($fp) / $R1;
    var $Q2 = (pow($D, 2) / 2.0);
    var $Q3 = (5 + 3 * $T1 + 10 * $C1 - 4 * pow($C1, 2) - 9 * $e2) * pow($D, 4) / 24.0;
    var $Q4 = (61 + 90 * $T1 + 298 * $C1 + 45 * pow($T1, 2) - 3 * pow($C1, 2) - 252 * $e2) * pow($D, 6) / 720.0;
    var $lat = $fp - $Q1 * ($Q2 - $Q3 + $Q4);

    var $Q5 = $D;
    var $Q6 = (1 + 2 * $T1 + $C1) * pow($D, 3) / 6;
    var $Q7 = (5 - 2 * $C1 + 28 * $T1 - 3 * pow($C1, 2) + 8 * $e2 + 24 * pow($T1, 2)) * pow($D, 5) / 120.0;
    var $lng = $lng0 + ($Q5 - $Q6 + $Q7) / cos($fp);

    $lat = ($lat * 180) / M_PI;
    $lng = ($lng * 180) / M_PI;

    return {
        y: $lat,
        x: $lng
    };
}
//#region 圖層摺疊+-符號切換

$(document).on('click', '.toggleLayerIcon', function (e) {

    //console.log($(this).hasClass("2ndCard"));
    $(this).parents('.card.1stCard')
        .siblings().find('.fa-minus-circle')
        .toggleClass('fa-minus-circle', 'fa-plus-circle');
    $(this).find('i').toggleClass('fa-minus-circle', 'fa-plus-circle');
});

//#endregion 圖層摺疊+-符號切換
//#region 縣市、鄉鎮
function townItemhtml(htmlcontent, t) {
    var html = '<a class="dropdown-item" href="#!" data-value="' + t + '" >' + htmlcontent + '</a>';
    return html;
}
var CountyGeoLayer = null;
$(document).on('click', '#countyItem .dropdown-item', function () {
    //選取縣市值填入btn
    var thisval = $(this).data();
    var thistext = $(this).text();
    $('#countyname').text(thistext)
        .data('param', thisval);
    var data = { county: thistext, c: thisval };
    //console.log("thistext");
//console.log(thistext);
    $('#townname').text("未選擇").data('param', '');
    $('#townItem').empty();
    $('#townItem').append(townItemhtml('未選擇'));
    if (TownGeoLayer !== null) {
        TownGeoLayer.onRemove(map);
    }
    if (CountyGeoLayer !== null) {
        CountyGeoLayer.onRemove(map);
    }

    if (thistext !== "未選擇") {
        // 顯示縣市界
        AjaxCall('GetCountyGeo', data, function (result) {
            //console.log('GetCountyGeoresult');
            //console.log(result);
            var _Result = (result.hasOwnProperty('d')) ? result.d : result;
            /*取得的縣市加入地圖- */
            //console.log(map);
            //map.removeLayer(TownGeoLayer);

            CountyGeoLayer = L.geoJSON(_Result, {
                style: {
                    'color': 'blue',
                    'weight': 5,
                    'opacity': 1,
                    'fillColor': 'blue',
                    'fillOpacity': 0.1
                }
            }).addTo(map);
            map.fitBounds(CountyGeoLayer.getBounds());
            //console.log('CountyGeoLayer');
           // console.log(CountyGeoLayer);
        });

        //取得鄉鎮市清單
        AjaxCall('GetTownList', data, function (result) {
            $('#townItem').empty();
            $('#townItem').append(townItemhtml('未選擇'));
            $(result).each(function () {
                $('#townItem').append(townItemhtml(this.townname, this.t));
            });
        });
    }
});
var TownGeoLayer = null;
$(document).on('click', '#townItem .dropdown-item', function () {
    //選取鄉鎮市值填入btn
    var thisval = $(this).data();
    var thistext = $(this).text();
    $('#townname').text(thistext)
        .data('param', thistext);
    var data = { t: thisval.value };
    clearAreaLayer();//移除縣市鄉鎮市圖層
    clearQueryLayer();//移除查詢結果圖層
    hideResultbar();//隱藏商家詳細資料
    //顯示鄉鎮市界
    if (thistext !== "未選擇") {
        CountyGeoLayer.onRemove(map);
        {
            AjaxCall('GetTownGeo', data, function (result) {
                var _Result = (result.hasOwnProperty('d')) ? result.d : result;
                /*取得的鄉鎮市加入地圖- */
                //console.log(map);
                //map.removeLayer(TownGeoLayer);
                TownGeoLayer = L.geoJSON(_Result, {
                    style: {
                        'color': 'red',
                        'weight': 5,
                        'opacity': 1,
                        'fillColor': 'white',
                        'fillOpacity': 0.1
                    }
                }).addTo(map);//;
                map.fitBounds(TownGeoLayer.getBounds());
               
            });
        }

    } else {
        $('#townname').text("未選擇").data('param', '');
        CountyGeoLayer.onAdd(map);
        map.fitBounds(CountyGeoLayer.getBounds());
    }

});
// #endregion 縣市、鄉鎮
// #region 全選/取消
$(document).on('click', '#badgehotelAll', function () {
    var _this = $(this);
    var isAll = _this.prop("checked");
    //設定checkbox選取
    $("#badgehotelCardbody").find('input:checkbox').not(this).prop('checked', this.checked);
    //選取標籤切換
    if (isAll) {
        $("#greenHotelCardheading").find('.selected.circle').show();

    } else {
        $("#greenHotelCardheading").find('.selected.circle').hide();
    }
});
$(document).on('click', '#inteCaseAll', function () {
    var _this = $(this);
    var isAll = _this.prop("checked");
    //設定checkbox選取
    $("#hotelCardbody").find('input:checkbox').not(this).prop('checked', this.checked);
    //選取標籤切換
    if (isAll) {
        $("#greenHotelCardheading").find('.selected.rec').show();

    } else {
        $("#greenHotelCardheading").find('.selected.rec').hide();
    }
});
$(document).on('click', '#storeAll', function () {
    var _this = $(this);
    var isAll = _this.prop("checked");
    //設定checkbox選取
    $("#storeCardbody").find('input:checkbox').not(this).prop('checked', this.checked);
    //選取標籤切換
    if (isAll) {
        $("#storeCardheading").find('.selected.rec').show();

    } else {
        $("#storeCardheading").find('.selected.rec').hide();
    }
});
//#region 環保餐廳全部餐廳與條件選項相斥
$(document).on('click', '#allRestaurant', function () {
    var _this = $(this);
    var isAll = _this.prop("checked");
    //設定checkbox選取
    _this.parents('.collapse').find('input:checkbox').not(this).prop('checked', false);

    //選取標籤切換
    _this.parents('.collapse').prev().find('.selected').hide();
    //_this.parents('.collapse').prev().find('.selected').not($(".EcoHotel")).hide();

});
//#endregion 環保餐廳全部餐廳與條件選項相斥
// #endregion 全選/取消
// #region 取消單項時全選取消勾選/環保餐廳取消全部餐廳勾選

$(document).on('click', ' input:checkbox', function () {
    var _this = $(this);
    var thisvalue = _this.val();
    var isAll = _this.parent().parent().find("input:checkbox").eq(0).prop('checked');
    //非點擊全選時
    if (thisvalue !== "all") {
        if (isAll) {  //已為全選時，取消checkbox全選選項
            _this.parent().parent().find("input:checkbox").eq(0).prop('checked', false);
        }
        var selectedclass = "." + _this.prop("id");
        _this.parents('.collapse').prevAll().find(selectedclass).toggle();//選取標籤切換
    }
});

// #endregion 取消單項時全選取消勾選/環保餐廳取消全部餐廳勾選


//#region 查詢section
// #region 宣告圖層變數
var restaurant_Layer = null;//環保餐廳
var badgeHotel_Layer = null;//環保旅店
var hotel_Layer = null;//環保旅店
var store_Layer = null;
//var Chainstore_Y_Layer = null;//連鎖型綠色商店
//var Chainstore_N_Layer = null;//非連鎖型綠色商店
var other_Layer = null;//其他
var preMarker;
// #endregion 宣告圖層變數

//#region Icon定義
var restaurantIcon = L.divIcon({
    className: 'restaurant',
    iconSize: [20, 20]
});
var badgehotel_g = L.divIcon({
    className: 'badgehotel_g',
    iconSize: [20, 20]
});
var badgehotel_s = L.divIcon({
    className: 'badgehotel_s',
    iconSize: [20, 20]
});
var badgehotel_c = L.divIcon({
    className: ' badgehotel_c',
    iconSize: [20, 20]
});
var hotel = L.divIcon({
    className: 'hotel',
    iconSize: [20, 20]
});
var Chainstore_Y = L.divIcon({
    className: 'Chainstore_Y',
    iconSize: [20, 20]
});
var Chainstore_N = L.divIcon({
    className: 'Chainstore_N',
    iconSize: [20, 20]
});
//#endregion Icon定義 
//#region 光圈Icon定義
var restaurant_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: '#28a745',
    fillColor: '#28a745',
    heartbeat: 0.7,
    subClassName: 'restaurant_Pulsing'
});
var badgehotel_g_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: 'gold',
    fillColor: 'gold',
    heartbeat: 0.7,
    subClassName: 'badgehotel_g_Pulsing'
});
var badgehotel_s_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: '#6495ed',
    fillColor: '#6495ed',
    heartbeat: 0.7,
    subClassName: 'badgehotel_s_Pulsing'
});
var badgehotel_c_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: 'coral',
    fillColor: 'coral',
    heartbeat: 0.7,
    subClassName: 'badgehotel_c_Pulsing'
});
var hotel_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: '#b200ff',
    fillColor: '#b200ff',
    heartbeat: 0.7,
    subClassName: 'hotel_Pulsing'
});
var Chainstore_Y_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: '#f68be7',
    fillColor: '#f68be7',
    heartbeat: 0.7,
    subClassName: 'Chainstore_Y_Pulsing'
});
var Chainstore_N_PulsingIcon = L.icon.pulse({
    iconSize: [20, 20],
    color: '#eaaa7c',
    fillColor: '#eaaa7c',
    heartbeat: 0.7,
    subClassName: 'Chainstore_N_Pulsing'
});

//#endregion 光圈Icon定義
//#region 查詢click
$(document).on('click', '#search', function () {

    //#region 宣告查詢參數變數
    var paramcounts = 0;//選擇商家種類選取數量
    var _paramAll = {};
    var activeItem = [];  // 環保餐廳餐與活動項目
    var gradeItem = [];  //環保旅宿標章等級項目
    var inteCaseTypeItem = [];  //環保旅宿標章等級項目
    var storeClassItem = [];  //環保旅宿標章等級項目
    //#endregion 宣告參數變數
    // #region 取得各圖層查詢參數
    $('#sidebar input').each(function () {
        var _this = $(this);
        var _param = _this.data("param");
        var _name = _this.prop("name");
        var isCheckbox = _this.prop("type") === 'checkbox';
        if (isCheckbox && _this.prop("checked")) { //選擇商家種類選取數量
            paramcounts++;
        }
        if (_param === 'restaurant') { // 環保餐廳參數
            if (_this.prop("checked") === true) {
                activeItem.push(_this.val());
            }
        } else if (_param === 'badgehotel') { //環保標章旅宿參數
            if (_this.prop("checked") === true) {
                gradeItem.push(_this.val());
            }
        } else if (_param === 'ecoHotel') { //環保旅宿參數
            if (_this.prop("checked") === true) {
                inteCaseTypeItem.push(_this.val());
            }
        } else if (_param === 'storeClass') { //綠色商店參數
            if (_this.prop("checked") === true) {
                storeClassItem.push(_this.val());
            }
        }
    });
    if (activeItem.length > 0) {
        _paramAll.a = activeItem.join(','); //a:參加活動
    }
    if (activeItem[0] === 'all') {
        _paramAll.a = ''; //a:參加活動
    }
    if (gradeItem.length > 0) {
        _paramAll.h = 2; //h:HotelType 標章旅館
        _paramAll.m = gradeItem.join(',');// m:活動介紹及環保作為或級別(環保標章旅宿等級參數)
    }
    if (inteCaseTypeItem.length > 0) {
        _paramAll.ic = inteCaseTypeItem.join(',');//ic:優惠方案大補包
    }
    if (storeClassItem.length > 0) {
        _paramAll.sc = storeClassItem.join(',') == 'A,B' ? 'C' : storeClassItem.join(',');//sc:商店類型(連鎖/非連鎖)

    }

    // #endregion 取得各圖層查詢參數
    // #region 取得縣市、鄉鎮市參數

    _paramAll["c"] = $('#countyname').data('param').value;
    _paramAll["zn"] = $('#townname').data('param');
    _paramAll["cn"] = $('#countyname').text();
    // #endregion 取得縣市、鄉鎮市參數
    if ($('#countyname').data('param') === '未選擇' || $('#countyname').data('param').value === '') {
        alert("請選擇縣市/鄉鎮市");
        return;
    }
    else if (paramcounts === 0) {
        alert("請選擇商家種類");
        return;
    }
    //$('#restaurant_list').empty();
    //$('#badgehotel_list').empty();
    //$('#hotel_list').empty();
    clearResultList();
    hideResultbar();//隱藏商家詳細資料
    clearQueryLayer();//移除圖層

    if (activeItem.length !== 0) {
        getRestaurants(_paramAll);
    }
    if (_paramAll.m) {
        _paramAll.h = 2;//h:HotelType 標章旅館
        getBadgeHotels(_paramAll);
    }
    if (inteCaseTypeItem.length !== 0) {
        _paramAll.h = 1;//h:HotelType環保旅店
        getEcoHotels(_paramAll);
    }
    if (storeClassItem.length !== 0) {
        getStores(_paramAll);

    }

});

//#endregion 查詢click
//#endregion  查詢section

//#region 重設
$(document).on('click', '#reset', function () {
    $('#countyname').text('未選擇').data('param', '未選擇');
    $('#townItem').empty().append(townItemhtml('未選擇'));
    $('#townname').text('未選擇').data('param', '');
    $('#sidebar input').each(function () {
        $(this).prop("checked", false);
    });
    $('.selected').hide();
    $('#listBtn').hide();
    clearQueryLayer();//清除查詢結果圖層
    hideResultbar(); //隱藏商家詳細資料
    clearResultList();//清除查詢清冊
});
//清除查詢清冊
function clearResultList() {
    $('#restaurant_list').empty();
    $('#badgehotel_list').empty();
    $('#hotel_list').empty();
    $('#store_list').empty();
}
//隱藏商家詳細資料
function hideResultbar() {
    $('#resultbar_restaurant').hide();
    $('#resultbar_badgehotel').hide();
    $('#resultbar_hotel').hide();
    $('#resultbar_store').hide();
}
//清除縣市鄉鎮市圖層
function clearAreaLayer() {
    if (CountyGeoLayer !== null) {
        CountyGeoLayer.onRemove(map);
    }
    if (TownGeoLayer !== null) {
        TownGeoLayer.onRemove(map);
    }
}
//清除查詢結果圖層
function clearQueryLayer() {

    if (restaurant_Layer !== null) {
        restaurant_Layer.onRemove(map);
    }
    if (badgeHotel_Layer !== null) {
        badgeHotel_Layer.onRemove(map);
    }

    if (hotel_Layer !== null) {
        hotel_Layer.onRemove(map);
    }
    if (store_Layer !== null) {
        store_Layer.onRemove(map);
    }
    if (other_Layer !== null) {
        other_Layer.onRemove(map);
    }
}
//#endregion 重設

//#region api跨網域測試 待刪除

$("#testbtn").click(function () {

    var options = {
        c: "f",
        a: '1,2',
    };
    getRestaurants("http://greenliving.eri.com.tw/PublicRwd/APIs/RestaurantGIS?", options);
});
//#endregion api 跨網域測試 待刪除
//#region 取得環保餐廳清冊及布點fun
var DataMark = [];
function getRestaurants(options) {
    //var url = "http://greenliving.eri.com.tw/PublicRwd/APIs/RestaurantGIS?";
    //console.log('getRestaurantsMapServerUrl[1]');
    //console.log(MapServerUrl[1]);
    var url = MapServerUrl[1] + "APIs/RestaurantGIS?";
   
    $.getJSON(url, options)
        .done(function (json) {
            if (json.Result === 'Success') {
                if (json.RowsCount >= 1) {
                    var index = 0;//查詢清單序號
                    restaurant_Layer = new L.layerGroup().addTo(map);//定義圖層
                    //#region 定義聚類圖
                    var markers = L.DonutCluster({
                        chunkedLoading: true
                    }, {
                        key: 'title',
                        //, sumField: 'value'
                        //order:['A', 'B' ],
                        //title: {A:' ', B:' '},
                        arcColorDict: {
                            restaurant: '#28a745', //環保餐廳
                            otherdata: 'Blue'//其他
                        }
                    });
                    //#endregion 定義聚類圖
                    DataMark = [];//點位陣列
                    var k = 0;//點位陣列index
                    // #region 佈點、列清冊、點事件
                    $(json.Detail).each(function () {
                        //#region 列清單
                        index++;
                       
                        var latlng = this.Latitude + ',' + this.Longitude;
                        var listHtml_a = '<a href="#" id=' + this.Id + ' class=" font-weight-bold " onclick="setLocation(' + latlng + ' );getRestaurantDetail({id:' + this.Id + '},' + k + ')"><span>' + index + '</span><span>' + this.Name + '</span></a>';
                        var listHtml_shopGift = '<span class="circle shopGift selected" title="來店禮" style="display:none">禮</span>';
                        var listHtml_Point = '<span class="circle consumptionPoint selected" title="消費贈點"  style="display:none">點</span>';
                        var listHtml_Discount = '<span class="circle pointsDiscount selected" title="點數折抵"  style="display:none">抵</span>';
                        var listHtml_greenPoint = '<span class="circle greenPoint selected" title="環保集點" >環</span>';
                        var id = '#' + this.Id;

                        $('#restaurant_list').append(listHtml_a);
                        if (this.Active.indexOf("1") >= 0) {
                            $(id).append(listHtml_shopGift);
                        }
                        if (this.Active.indexOf("2") >= 0) {
                            $(id).append(listHtml_Point);
                        }
                        if (this.Active.indexOf("3") >= 0) {
                            $(id).append(listHtml_Discount);
                        }
                        if (this.Active.indexOf("4") >= 0) {
                            $(id).append(listHtml_greenPoint);
                        }
                        //#endregion 列清單
                        // #region 定義圓環分類顏色
                        //console.log(a);
                        var _bg = "#28a745";
                        var titlecontent = 'restaurant';
                        var Layer = restaurant_Layer;
                        // #endregion 圓環分類顏色

                        // #region 佈點及click事件顯示詳細資料
                        DataMark[k] = L.marker([this.Latitude, this.Longitude], {
                            title: titlecontent,
                            //radius: 8,
                            //fillColor: _bg,
                            //color: "#aaaaaa",
                            //weight: 1,
                            //opacity: 1,
                            //fillOpacity: 0.9,
                            makerIndex: k,
                            id: this.Id,
                            icon: restaurantIcon,
                            plushIcon: restaurant_PulsingIcon
                            //className: 'test'
                        }).on('click', function (e) {

                            var _makerIndex = this.options.makerIndex;
                            removePulsing();//移除光圈
                            //#region 加光圈
                            ////加光環
                            e.target.setIcon(restaurant_PulsingIcon);
                            preMarker = e.target;
                           
                            $(".lpi-pulse").css("border-color", "white");
                            //#endregion 加光圈


                            var _id = this.options.id;
                            //alert(_id);
                            if (_id) {
                                getRestaurantDetail({ id: _id }, _makerIndex);

                            }
                            map.setView([e.latlng.lat, e.latlng.lng], 18);
                        }).addTo(markers).addTo(Layer);


                        //markers.addLayer(DataMark[k]).addTo(Layer);
                        // #endregion 佈點及click事件顯示詳細資料


                        k++;
                    });
                    // #endregion 佈點、列清冊、點事件
                    if (TownGeoLayer) {
                        map.fitBounds(TownGeoLayer.getBounds());
                    } else map.fitBounds(CountyGeoLayer.getBounds());
                } else {
                    $('#restaurant_list').append("<a class='text-center'>無資料</a>");
                }
            } else {
                //alert(json.Result);
                $('#restaurant_list').append("<a class='text-center'>無資料</a>");
                console.log("Request done but  error: " + json.Result);
            }
            $('#listBtn').show();
            $('#resultbar_list').show();
            $('#resultTab a:first').tab('show');
            $('#sidebar').hide();
           


        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
}
//#endregion 取得環保餐廳清冊及布點fun
//#region 取得環保餐廳詳細資料fun
function getRestaurantDetail(id, k) {
    removePulsing();//移除光圈
    //#region 加光圈

  
    DataMark[k].setIcon(restaurant_PulsingIcon);
    //DataMark[k].setOpacity(0.7);
    preMarker = DataMark[k];
  
    $(".lpi-pulse").css("border-color", "white");
    //#endregion 加光圈



    //var url = 'http://greenliving.eri.com.tw/PublicRwd/APIs/RestaurantGISInfo?';
    var url = MapServerUrl[1] + 'APIs/RestaurantGISInfo?';

    $.getJSON(url, id)
        .done(function (json) {
            
            if (json.Result === 'Success') {
                //alert("getRestaurantDetail");
                $(json.Detail).each(function () {
                    $('.detailResult').hide();
                    var activityItem = this.Active.replace('1', '來店禮');
                    activityItem = activityItem.replace('2', '消費贈點');
                    activityItem = activityItem.replace('3', '點數折抵');
                    activityItem = activityItem.replace('4', '環保集點');
                    $("#photo_restaurant").prop("src", this.RestPicList[0].RestUrl);
                    $("#names_restaurant").text(this.Name);
                    $("#GUInumber_restauran").text(this.LicenseNo);
                    $("#description_restaurant").text(this.Introduction);
                    if (activityItem =="環保集點") {
                        $("#activityItem_restauran").text(activityItem);
                    }
                    $("#tel_restaurant").text(this.Phone);
                    $("#address_restaurant").text(this.Address);
                    $("#website_restaurant").prop("href", this.OfficialWebsite);
                   
                    $('#resultbar_restaurant').show();
                    setResultbarListWindows();
                });
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
}
//#endregion 取得環保餐廳詳細資料fun
//#region 取得環保標章旅館清冊及布點fun
var BadgeHotelDataMark = [];
function getBadgeHotels(options) {
    var url = MapServerUrl[1] + "APIs/HotelsGIS?";
    
    $.getJSON(url, options)
        .done(function (json) {
            console.log(json);
            if (json.Result === 'Success') {
                if (json.RowsCount >= 1) {
                    
                    var index = 0;//查詢清單序號
                    badgeHotel_Layer = new L.layerGroup().addTo(map);//定義圖層
                    //#region 定義聚類圖
                    var markers = L.DonutCluster({
                        chunkedLoading: true
                    }, {
                        key: 'title',
                        //, sumField: 'value'
                        //order:['A', 'B' ],
                        //title: {A:' ', B:' '},
                        arcColorDict: {
                            金級環保標章旅館: 'gold',//金級標章旅館
                            銀級環保標章旅館: '#6495ed',//銀級標章旅館
                            銅級環保標章旅館: 'coral',//銅級標章旅館
                            //其他: 'Blue'//其他
                        }
                    });
                    //#endregion 定義聚類圖
                    BadgeHotelDataMark = [];//點位陣列
                    var k = 0;//點位陣列index
                    // #region 佈點、列清冊、點事件
                    $(json.Detail).each(function () {
                       
                        //#region 列清單
                        index++;
                        var titlecontent = '';
                        var icon = hotel;
                        var plushIcon = hotel_PulsingIcon;
                        var plushIconUI = '';
                       
                        var latlng = this.Lat + ',' + this.Lon;
                        var istHtml_badgehotel_g = '<span class="circle badgehotel_g selected">金</span>';
                        var istHtml_badgehotel_s = '<span class="circle badgehotel_s selected ">銀</span>';
                        var istHtml_badgehotel_c = '<span class="circle badgehotel_c selected">銅</span>';
                        //var istHtml_EcoHotel = '<span class="selected circle EcoHotel">環</span>';
                        var id = '#' + this.Num;
                        var isthtmlspan;
                        if (this.Memo === '金級環保旅館') {
                            titlecontent = '金級環保標章旅館';
                            icon = badgehotel_g;
                            plushIcon = badgehotel_g_PulsingIcon;
                            plushIconUI = 'badgehotel_g_PulsingIcon';
                            isthtmlspan = istHtml_badgehotel_g;
                        } else if (this.Memo === '銀級環保旅館') {
                            titlecontent = '銀級環保標章旅館';
                            icon = badgehotel_s;
                            plushIcon = badgehotel_s_PulsingIcon;
                            plushIconUI = 'badgehotel_s_PulsingIcon';
                            isthtmlspan = istHtml_badgehotel_s;
                        } else if (this.Memo === '銅級環保旅館') {
                            titlecontent = '銅級環保標章旅館';
                            icon = badgehotel_c;
                            plushIcon = badgehotel_c_PulsingIcon;
                            plushIconUI = 'badgehotel_c_PulsingIcon';
                            isthtmlspan = istHtml_badgehotel_c;
                        }
                        //else if (this.Memo !== '') {
                        //    titlecontent = '環保旅店';
                        //    icon = hotel;
                        //    plushIcon = hotel_PulsingIcon;
                        //    plushIconUI = 'hotel_PulsingIcon';
                        //    isthtmlspan = istHtml_EcoHotel;
                        //} 
                        var listHtml_a = '<a href="#" id=' + this.Num + ' class=" font-weight-bold HotelDetail" onclick="setLocation(' + latlng + ' );getBadgeHotelDetail({id:' + this.Num + ',type:' + this.HotelType + '},' + k + ',' + plushIconUI + ')"><span>' + index + '</span><span>' + this.Name + '</span></a>';
                        $('#badgehotel_list').append(listHtml_a);
                        $(id).append(isthtmlspan);
                        //#endregion 列清單
                        // #region 定義圓環分類顏色
                        
                        var _bg = "#28a745";
                        //var titlecontent = 'hotel';
                        var Layer = badgeHotel_Layer;
                        // #endregion 圓環分類顏色
                        // #region 佈點及click事件顯示詳細資料
                        BadgeHotelDataMark[k] = L.marker([this.Lat, this.Lon], {
                            title: titlecontent,
                            makerIndex: k,
                            id: this.Num,
                            icon: icon,
                            plushIcon: plushIcon,
                            HotelType: this.HotelType
                        }).on('click', function (e) {
                            var _makerIndex = this.options.makerIndex;
                            removePulsing();//移除光圈
                            e.target.setIcon(plushIcon);//加光環
                            preMarker = e.target;
                            var _id = this.options.id;
                            var _HotelType = this.options.HotelType;
                            //alert(_id);
                            if (_id) {
                                getBadgeHotelDetail({ id: _id, type: _HotelType }, _makerIndex, plushIcon);
                            }
                            map.setView([e.latlng.lat, e.latlng.lng], 18);
                        }).addTo(markers).addTo(Layer);
                        // #endregion 佈點及click事件顯示詳細資料
                        k++;
                    });
                    // #endregion 佈點、列清冊、點事件
                    if (TownGeoLayer) {
                        map.fitBounds(TownGeoLayer.getBounds());
                    } else map.fitBounds(CountyGeoLayer.getBounds());
                } else {
                    $('#badgehotel_list').append("<a class='text-center'>無資料</a>");
                }
            } else {
                //alert(json.Result);
                $('#badgehotel_list').append("<a class='text-center'>無資料</a>");
                console.log("Request done but  error: " + json.Result);
            }
            $('#listBtn').show();
            $('#resultbar_list').show();
            $('#resultTab a:first').tab('show');
            $('#sidebar').hide();

        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
}
//#endregion 取得環保環保標章旅館清冊及布點fun
//#region 取得環保環保標章旅館詳細資料fun
function getBadgeHotelDetail(data, k, plushIcon) {

    var plushIconU = getPlushIconU(plushIcon);//取得光圈樣式
    removePulsing();//移除光圈
    BadgeHotelDataMark[k].setIcon(plushIconU);//加光圈
    preMarker = BadgeHotelDataMark[k];
    var url = MapServerUrl[1] + 'APIs/Hotels2?';
   
    $.getJSON(url, data)
        .done(function (json) {
            //console.log(json);
            $('.detailResult').hide();
            if (json.Result === 'Success') {
                $(json.Detail).each(function () {
                 
                    var classname = '';
                    if (this.Memo === '金級環保旅館') {
                        classname = 'badgehotel_g';
                    } else if (this.Memo === '銀級環保旅館') {
                        classname = 'badgehotel_s';
                    } else if (this.Memo === '銅級環保旅館') {
                        classname = 'badgehotel_c';
                    }
                    var grade = this.Memo.replace('環保旅館', '環保標章旅宿');
                    $("#badgeGrade").text(grade).removeClass().addClass('m-0').addClass('rec').addClass(classname);
                    $("#photo_badgehotel").prop("src", this.ImgByte);
                    $("#names_badgehotel").text(this.Name);
                    $("#address_badgehotel").text(this.Address);
                    $('#resultbar_badgehotel').show();
                    setResultbarListWindows();
                });
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
}
//#endregion 取得環保標章旅館詳細資料fun
//#region 取得環保旅店清冊及布點清冊及布點fun
var EcoHotelDataMark = [];
function getEcoHotels(options) {
    var url = MapServerUrl[1] + "APIs/HotelsGIS?";
   
    $.getJSON(url, options)
        .done(function (json) {

            if (json.Result === 'Success') {
                if (json.RowsCount >= 1) {
                   
                    var index = 0;//查詢清單序號
                    hotel_Layer = new L.layerGroup().addTo(map);//定義圖層
                    //#region 定義聚類圖
                    var markers = L.DonutCluster({
                        chunkedLoading: true
                    }, {
                        key: 'title',
                        arcColorDict: {
                            環保旅店: '#b200ff',//環保旅店
                            //其他: 'Blue'//其他
                        }
                    });
                    //#endregion 定義聚類圖
                    EcoHotelDataMark = [];//點位陣列
                    var k = 0;//點位陣列index
                    // #region 佈點、列清冊、點事件
                    $(json.Detail).each(function () {
                        //console.log(this);
                        //#region 列清單
                        index++;
                        var titlecontent = '';
                        var icon = hotel;
                        var plushIcon = hotel_PulsingIcon;
                        var plushIconUI = '';
                        //this.Lat = 25.04393501; //待測試無誤後刪除
                        //this.Lon = 121.50852501 + index * 0.001; //待測試無誤後刪除
                        var latlng = this.Lat + ',' + this.Lon;
                        var istHtml_inteCase1 = '<span class="rec inteCase1 selected">一</span>';
                        var istHtml_inteCase2 = '<span class="rec inteCase2 selected ">二</span>';
                        var istHtml_inteCase3 = '<span class="rec  inteCase3 selected">三</span>';
                        var id = '#' + this.Num;
                        var isG = this.Memo === '金級環保旅館';
                        var isS = this.Memo === '銀級環保旅館';
                        var isC = this.Memo === '銅級環保旅館';
                        if (!isG && !isS && !isC && this.Memo !== '') {
                            titlecontent = '環保旅店';
                            icon = hotel;
                            plushIcon = hotel_PulsingIcon;
                            plushIconUI = 'hotel_PulsingIcon';
                        }
                        var listHtml_a = '<a href="#" id=' + this.Num + ' class=" font-weight-bold HotelDetail" onclick="setLocation(' + latlng + ' );getEcoHotelDetail({id:' + this.Num + ',type:' + this.HotelType + '},' + k + ',' + plushIconUI + ')"><span>' + index + '</span><span>' + this.Name + '</span></a>';
                        $('#hotel_list').append(listHtml_a);
                        var inteCaseVal1 = this.InteCaseList[0].InteCase1;
                        var inteCaseVal2 = this.InteCaseList[0].InteCase2;
                        var inteCaseVal3 = this.InteCaseList[0].InteCase3;

                        if (inteCaseVal1 === "1") {
                           
                            $(id).append(istHtml_inteCase1);
                        }
                        if (inteCaseVal2 === "1") {
                            $(id).append(istHtml_inteCase2);
                        }
                        if (inteCaseVal3 === "1") {
                            $(id).append(istHtml_inteCase3);
                        }

                        //#endregion 列清單
                        // #region 定義圓環分類顏色
                        
                        var _bg = "#28a745";
                        //var titlecontent = 'hotel';
                        var Layer = hotel_Layer;
                        // #endregion 圓環分類顏色
                        // #region 佈點及click事件顯示詳細資料
                        EcoHotelDataMark[k] = L.marker([this.Lat, this.Lon], {
                            title: titlecontent,
                            makerIndex: k,
                            id: this.Num,
                            icon: icon,
                            plushIcon: plushIcon,
                            HotelType: this.HotelType
                        }).on('click', function (e) {
                            var _makerIndex = this.options.makerIndex;
                            removePulsing();//移除光圈
                            //#region 加光圈
                            ////加光環
                            e.target.setIcon(plushIcon);
                            preMarker = e.target;
                            
                            $(".lpi-pulse").css("border-color", "white");
                            //#endregion 加光圈
                            var _id = this.options.id;
                            var _HotelType = this.options.HotelType;
                            //alert(_id);
                            if (_id) {
                                getEcoHotelDetail({ id: _id, type: _HotelType }, _makerIndex, plushIcon);
                            }
                            map.setView([e.latlng.lat, e.latlng.lng], 18);
                        }).addTo(markers).addTo(Layer);
                        // #endregion 佈點及click事件顯示詳細資料
                        k++;
                    });
                    // #endregion 佈點、列清冊、點事件
                    if (TownGeoLayer) {
                        map.fitBounds(TownGeoLayer.getBounds());
                    } else map.fitBounds(CountyGeoLayer.getBounds());
                } else {
                    $('#hotel_list').append("<a class='text-center'>無資料</a>");
                }
            } else {
                //alert(json.Result);
                $('#hotel_list').append("<a class='text-center'>無資料</a>");
                console.log("Request done but  error: " + json.Result);
            }
            $('#listBtn').show();
            $('#resultbar_list').show();
            $('#resultTab a:first').tab('show');
            $('#sidebar').hide();

        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
}
//#endregion 取得 環保旅店清冊及布點fun
//#region 取得環保旅店詳細資料fun
function getEcoHotelDetail(data, k, plushIcon) {
    var plushIconU = getPlushIconU(plushIcon);//取得光圈樣式
    removePulsing();//移除光圈
    EcoHotelDataMark[k].setIcon(plushIconU);//加光圈
    preMarker = EcoHotelDataMark[k];
    var url = MapServerUrl[1] + 'APIs/Hotels2?';
    $.getJSON(url, data)
        .done(function (json) {
            $('.detailResult').hide();
            if (json.Result === 'Success') {
                $(json.Detail).each(function () {
                    //console.log(this);
                    $("#inteCase_hotel").empty().removeClass('d-inline-block');
                    var inteCaseCount = 0;
                    var inteHtmlStr1 = '<div class="m-0 rec text-white inteCase1 wh-unset " >方案一</div><label  class="control-label  text-white ">消費者優惠</label><br/>';
                    var inteHtmlStr2 = '<div class="m-0 rec text-white inteCase2 wh-unset">方案二</div><label  class="control-label  text-white ">贊助環保活動</label><br/>';
                    var inteHtmlStr3 = '<div class="m-0 rec text-white inteCase3 wh-unset　">方案三</div><label  class="control-label  text-white ">提供環保客房</label><br/>';

                    if (this.InteCaseList[0].InteCase1 !== "0") {
                        $("#inteCase_hotel").append(inteHtmlStr1);
                        inteCaseCount++;
                    }
                    if (this.InteCaseList[0].InteCase2 !== "0") {
                        $("#inteCase_hotel").append(inteHtmlStr2);
                        inteCaseCount++;
                    }
                    if (this.InteCaseList[0].InteCase3 !== "0") {
                        $("#inteCase_hotel").append(inteHtmlStr3);
                        inteCaseCount++;
                    }
                    if (inteCaseCount === 0) {
                        inteHtmlStr = '<label id="tel_hotel" class="control-label  text-white ">無</label>';
                        $("#inteCase_hotel").append(inteHtmlStr).addClass('d-inline-block');
                    }
                    $("#photo_hotel").prop("src", this.ImgByte);
                    $("#names_hotel").text(this.Name);
                    $("#address_hotel").text(this.Address);
                    $("#tel_hotel").text(this.Phone);
                    $('#resultbar_hotel').show();
                    setResultbarListWindows();

                });
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });


}

//#endregion 取得環保旅宿詳細資料fun

//#region 取得綠色商店清冊及布點fun
var StoreDataMark = [];
function getStores(options) {
    var url = MapServerUrl[1] + "APIs/StoresGIS?";
    $.getJSON(url, options)
        .done(function (json) {
            $('#store_list').empty();
            if (json.Result === 'Success') {
                if (json.RowsCount >= 1) {
                    
                    var index = 0;//查詢清單序號
                    store_Layer = new L.layerGroup().addTo(map);//定義圖層
                    //#region 定義聚類圖
                    var markers = L.DonutCluster({
                        chunkedLoading: true
                    }, {
                        key: 'title',
                        //, sumField: 'value'
                        //order:['A', 'B' ],
                        //title: {A:' ', B:' '},
                        arcColorDict: {
                            連鎖型綠色商店: '#f68be7',//連鎖型綠色商店
                            非連鎖型綠色商店: '#eaaa7c',//非連鎖型綠色商店
                            // otherdata: 'Blue'//其他
                        }
                    });
                    //#endregion 定義聚類圖
                    StoreDataMark = [];//點位陣列
                    var k = 0;//點位陣列index
                    // #region 佈點、列清冊、點事件
                  
                    $(json.Detail).each(function () {
                        
                        //#region 列清單
                        index++;
                        var titlecontent = '';
                        var icon = Chainstore_Y;
                        var plushIcon = Chainstore_Y_PulsingIcon;
                        var plushIconUI = '';
                        var latlng = this.Lat + ',' + this.Lon;

                        var istHtml_Chainstore_Y = '<span class="selected rec text-dark Chainstore_Y ">連鎖</span>';
                        var istHtml_Chainstore_N = '<span class="selected rec  text-dark Chainstore_N">非連鎖</span>';
                        var storeId = this.StoreID;
                        if (storeId.indexOf("@") != -1) {
                            storeId = storeId.replace("\@", 'specialChar-at-')
                        }
                        var id = '#' + storeId;
                        var isthtmlspan;
                       
                        if (this.StoreClass === '連鎖型綠色商店') {
                            titlecontent = '連鎖';
                            icon = Chainstore_Y;
                            plushIcon = Chainstore_Y_PulsingIcon;
                            plushIconUI = 'Chainstore_Y_PulsingIcon';
                            isthtmlspan = istHtml_Chainstore_Y;
                        } else if (this.StoreClass === '非連鎖型綠色商店') {
                            titlecontent = '非連鎖';
                            icon = Chainstore_N;
                            plushIcon = Chainstore_N_PulsingIcon;
                            plushIconUI = 'Chainstore_N_PulsingIcon';
                            isthtmlspan = istHtml_Chainstore_N;
                        }
                        //var listHtml_a = '<a href="#" id=' + storeId + ' class=" font-weight-bold StoreDetail" onclick="setLocation(' + latlng + ' );getStoreDetail(' + this.StoreID + ',' + k + ',' + plushIconUI + ')"><span>' + index + '</span><span>' + this.StoreName + '</span></a>';
                        var listHtml_a = `<a href="#" id=${storeId} class=" font-weight-bold StoreDetail" onclick="setLocation(${latlng});getStoreDetail({id:'${this.StoreID}'} ,${k},${plushIconUI})"><span>${index}</span><span>${this.StoreName}</span></a> `;

                      
                        $('#store_list').append(listHtml_a);

                       
                        $(id).append(isthtmlspan);
                        //#region  待綠色商店功能測試無誤後刪除  
                        //if (this.Chainstore.indexOf("Y") >= 0) {
                        //    $(id).append(istHtml_Chainstore_Y);
                        //}
                        //if (this.Chainstore.indexOf("N") >= 0) {
                        //    $(id).append(istHtml_Chainstore_N);
                        //}
                        //#endregion 



                        //#endregion 列清單
                        // #region 定義圓環分類顏色
                        
                        var _bg = "#28a745";
                        var Layer = store_Layer;
                        // #endregion 圓環分類顏色

                        // #region 佈點及click事件顯示詳細資料
                        StoreDataMark[k] = L.marker([this.Lat, this.Lon], {
                            title: titlecontent,
                            makerIndex: k,
                            id: this.StoreID,
                            icon: icon,
                            plushIcon: plushIcon,
                        }).on('click', function (e) {
                            var _makerIndex = this.options.makerIndex;
                            removePulsing();//移除光圈
                            e.target.setIcon(plushIcon);//加光環
                            preMarker = e.target;
                            var _id = this.options.id;
                            if (_id) {
                                getStoreDetail({ id: _id }, _makerIndex, plushIcon);
                            }
                            map.setView([e.latlng.lat, e.latlng.lng], 18);
                        }).addTo(markers).addTo(Layer);


                        //markers.addLayer(DataMark[k]).addTo(Layer);
                        // #endregion 佈點及click事件顯示詳細資料
                        k++;
                    });
                    // #endregion 佈點、列清冊、點事件
                    if (TownGeoLayer) {
                        map.fitBounds(TownGeoLayer.getBounds());
                    } else map.fitBounds(CountyGeoLayer.getBounds());
                } else {
                    $('#store_list').append("<a class='text-center'>無資料</a>");
                }

            } else {
                //alert(json.Result);
                $('#store_list').append("<a class='text-center'>無資料</a>");
                console.log("Request done but  error: " + json.Result);
            }
            $('#listBtn').show();
            $('#resultbar_list').show();
            $('#resultTab a:first').tab('show');
            $('#sidebar').hide();
 

        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });

}
//#endregion 取得綠色商店清冊及布點fun

//#region 取得綠色商店詳細資料fun
function getStoreDetail(data, k, plushIcon) {
    var plushIconU = getPlushIconU(plushIcon);//取得光圈樣式
    removePulsing();//移除光圈
    StoreDataMark[k].setIcon(plushIconU);//加光圈
    preMarker = StoreDataMark[k];
    var url = MapServerUrl[1] + 'APIs/Stores2?';
    var goodClassUrl = MapServerUrl[1] + 'APIs/Stores2?';
   
    $.getJSON(url, data)
        .done(function (json) {
            $('.detailResult').hide();
            if (json.Result === 'Success') {
                //alert("getRestaurantDetail");
                $(json.Detail).each(function () {
                    
                    var classname = '';
                    if (this.StoreClass === '連鎖型綠色商店') {
                        classname = 'Chainstore_Y';
                    } else if (this.StoreClass === '非連鎖型綠色商店') {
                        classname = 'Chainstore_N';
                    }
                    var storeClass = this.StoreClass === '連鎖型綠色商店' ? "連鎖" : "非連鎖";

                    $("#storeClass").text(storeClass).removeClass().addClass('m-0').addClass('rec').addClass(classname);
                    $("#photo_store").prop("src", this.StorePic);
                    $("#names_store").text(this.StoreName);
                    $("#id_store").text(this.StoreID);
                    $("#tel_store").text(this.Phone);
                    $("#address_store").text(this.StoreAddr);
                    $("#contactPerson_store").prop("href", this.contactPerson_store);
                    $('#resultbar_store').show();
                    setResultbarListWindows();
                });
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });
    getStoreGoods(data);
}
//#endregion 取得綠色商店商品標章fun

function getStoreGoods(data) {
    var url = MapServerUrl[1] + 'APIs/StoreGoodClass?';
 
    var inteHtmlStr = "";
    $.getJSON(url, data)
        .done(function (json) {
           
            if (json.Result === 'Success') {
                $("#goodClass_store").empty().removeClass('d-inline-block');
                if (json.RowsCount >= 1) {
                    //alert("getRestaurantDetail");
                    json.Detail.forEach(function (item) {
                        inteHtmlStr = `<img class="m-0 goodsClass" src="${MapServerUrl[0]}/Content/images/GIS/GoodICon/${item}.png" loading="lazy" ></img>`;

                        $("#goodClass_store").append(inteHtmlStr);

                    });
                } else {
                    inteHtmlStr = '<label id="tel_hotel" class="control-label  text-white ">無</label>';
                    $("#goodClass_store").append(inteHtmlStr).addClass('d-inline-block');

                }
               
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });

}

//#region 
//#region 清單店家定位
function setLocation(lat, lng) {
    if (lat === 0 || lng === 0) {
        alert("該商家未提供座標");
    } else {
        map.setView([lat, lng], 18);
    }
}
//#endregion 清單店家定位

//#region 移除光圈
function removePulsing() {
    if (preMarker) {
        var markcss = $(preMarker)[0].options.icon.options.className;
        //console.log("QueryBufferFacPreMarkermarkcss");
      
        if (markcss.indexOf('lpi-restaurant_Pulsing') > -1) {
            preMarker.setIcon(restaurantIcon);
        } else if (markcss.indexOf('lpi-badgehotel_g_Pulsing') > -1) {
            preMarker.setIcon(badgehotel_g);
        } else if (markcss.indexOf('lpi-badgehotel_s_Pulsing') > -1) {
            preMarker.setIcon(badgehotel_s);
        } else if (markcss.indexOf('badgehotel_c_Pulsing') > -1) {
            preMarker.setIcon(badgehotel_c);
        } else if (markcss.indexOf('lpi-hotel_Pulsing') > -1) {
            preMarker.setIcon(hotel);
        } else if (markcss.indexOf('lpi-Chainstore_Y_Pulsing') > -1) {
            preMarker.setIcon(Chainstore_Y);
        } else {
            preMarker.setIcon(Chainstore_N);
        }
    }
}
//#endregion 移除光圈
//#region 取得光圈樣式
function getPlushIconU(plushIcon) {
    var plushIconU;
    
    if (plushIcon === 'badgehotel_g') {
        plushIconU = badgehotel_g_PulsingIcon;
    } else if (plushIcon === 'badgehotel_s') {
        plushIconU = badgehotel_s_PulsingIcon;
    } else if (plushIcon === 'badgehotel_c') {
        plushIconU = badgehotel_c_PulsingIcon;
    } else if (plushIcon === 'hotel') {
        plushIconU = hotel_PulsingIcon;
    } else {
        plushIconU = plushIcon;
    }
    return plushIconU;
}
//#endregion 取得光圈樣式

