Leaflet Markers

Leaflet中,Marker的使用方式非常简单,只需要给出坐标,然后添加到地图上就可以。

添加默认的Marker

例如,使用默认样式,添加一个marker:

  L.marker([50.5, 30.5]).addTo(map);

添加自定义的Marker

除了默认样式,还可以自定义Marker的大小、使用的图标,以及阴影的大小、位移大小等。 下面的例子展示了自定义这些属性的方法。

Step1 地图初始化

  var map = L.map('map').setView([51.5, -0.09], 13);

  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

Step2 定义Marker的样式,包括图标、大小、阴影等

  //定义图标的尺寸、阴影及尺寸等样式
  var LeafIcon = L.Icon.extend({
      options: {
          shadowUrl: 'http://leafletjs.com/docs/images/leaf-shadow.png',
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor:  [-3, -76]
      }
  });
  //定义Marker使用的图片
  var greenIcon = new LeafIcon({iconUrl: 'http://leafletjs.com/docs/images/leaf-green.png'}),
      redIcon = new LeafIcon({iconUrl: 'http://leafletjs.com/docs/images/leaf-red.png'}),
      orangeIcon = new LeafIcon({iconUrl: 'http://leafletjs.com/docs/images/leaf-orange.png'});
  //添加Marker
  L.marker([51.5, -0.09], {icon: greenIcon}).bindPopup("I am a green leaf.").addTo(map);
  L.marker([51.495, -0.083], {icon: redIcon}).bindPopup("I am a red leaf.").addTo(map);
  L.marker([51.49, -0.1], {icon: orangeIcon}).bindPopup("I am an orange leaf.").addTo(map);

Step3 把自定义的Marker添加到地图上

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

在线演示与源码编辑

您可以在线访问完整代码、体验演示效果,也可以直接在线编辑源码并实时查看效果。

results matching ""

    No results matching ""