簡體   English   中英

gmaps.js-遍歷元素並添加標記

[英]gmaps.js - loop through elements and add markers

使用gmaps.js如何遍歷類似(HTML)的內容:

<h1 id="location">Phuket</h1>

<div class="blist">
    <h3>Some hotel name</h3>
    <p>Adress 1</p>
</div>

<div class="blist">
    <h3>Another hotel name</h3>
    <p>Adress 2</p>
</div>

<div class="blist">
    <h3>Some name</h3>
    <p>Adress 3</p>
</div>

<div class="blist">
    <h3>Some other name</h3>
    <p>Adress 4</p>
</div>

..和:

  1. GEO代碼+在地圖上添加標記
  2. <h3>名稱添加到每個標記彈出窗口中
  3. 將鏈接添加到每個與之對應的彈出窗口(例如錨鏈接)
  4. 在所有GEO代碼鎖定中使用並添加#location,因為沒有該上下文,每個名稱不會說太多

我必須使用循環,但是即使搜索了幾個小時也沒有找到任何好的示例。 有人會認為這是一種普遍使用的方法..::)

檢查/使用jsFiddle基礎>>

gmaps適配器使這一過程變得微不足道。

var map = new GMaps({
    div: '#mapCanvas',
    lat: 0,
    lng: 52,
    zoom: 13,
    width: '400px',
    height: '300px'
});

var popupTemplate = '<div class="popupText"><h3>%1</h3><p>%2</p><p>%3</p></div>';

$(".blist").each(function() {
    var title = $(this).find("h3").text();
    var address = $(this).find("p.address").text();
    var tel = $(this).find("p.tel").text();
    GMaps.geocode({
        address: address,
        callback: function(results, status) {
            if (status == 'OK') {
                var latlng = results[0].geometry.location;
                map.setCenter(latlng.lat(), latlng.lng());
                map.addMarker({
                    lat: latlng.lat(),
                    lng: latlng.lng(),
                    title: title,
                    infoWindow: {
                        content: popupTemplate.replace('%1',title).replace('%2',address).replace('%3',tel)
                    }
                });
            }
        }
    });
});

演示

筆記:

  • 演示中用作地理編碼的倫敦酒店對普吉島的地址不可靠
  • 電話號碼字段已添加

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM