leaflet(二)在地圖上添加標記


地圖上添加標記使用L.marker接口

使用:第二個對象是可選的

L.marker( [ x , y ] , {

  //設置參數

  title:‘haha’ //鼠標hover出現title值

  draggable:true  //設置此參數后標記可拖動(移動)

}).addTo(mymap)

 

默認標記

var marker = L.marker([0, 0],{
    title:'景山',
    draggable:true
}).addTo(m);

 

 

自定義標記

借助L.icon接口。可以使用 自定義圖標

下面的代碼那個圖片就是圖標,哈哈

var myimage = L.icon({
    iconUrl:'./image.jpg', //圖片url
    iconSize:[50,100],     //設置圖片大小 寬度50.高度100
  
iconAnchor: [0,0] //設置定位點的位置。默認為中心 例子中以左上角為定位參考。相當於relative

  popupAnchor:[50 ,0], //設置警示框位置 ,以iconAnchor的值進行定位。相當於absolute 例子中的警示框定位到有、右上角。
    
})
var marker = L.marker([0, 0],{
   icon:myimage title:'景山', draggable:true }).addTo(m);
 

當我們需要很多共同點的圖標。例如只是圖片不一樣,但是圖片的大小,定位點,提示框的位置都是一樣的。

使用上面的就會創建很多相同屬性的圖標對象。這時候使用繼承。繼承父元素相同的屬性,然后在添加自己獨立的屬性

定義圖標類  ,把相同的屬性寫在這里

var LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: 'leaf-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});

實例化LeafIcon
var greenIcon = new LeafIcon({iconUrl: 'leaf-green.png'}),
  redIcon = new LeafIcon({iconUrl: 'leaf-red.png'}),
  orangeIcon = new LeafIcon({iconUrl: 'leaf-orange.png'});

//將標記添加到地圖中
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map).bindPopup("I am a green leaf.");
L.marker([51.495, -0.083], {icon: redIcon}).addTo(map).bindPopup("I am a red leaf.");
L.marker([51.49, -0.1], {icon: orangeIcon}).addTo(map).bindPopup("I am an orange leaf.");

 

在最開始的L.icon也是創建一個對象,只不過為了方便起見,使用方法返回一個對象

L.icon = function (options) {
    return new L.Icon(options);
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM