2017-11-11 785 views
0

我正在編寫一個應用程序,並且試圖使用Leaflet.js添加自定義標記。迄今爲止的代碼已工作,併成功向地圖添加了自定義標記,但是地圖上也存在默認標記。 使用Leaflet.js創建自定義標記在地圖上添加多個標記

var mymap = L.map('mapid').setView([-1.3938636,36.7442377], 13); 
    var mapdata = $.ajax({ 
     url: '/data.json', 
     dataType: 'text', 
     success: function(data) { 
      var geojson; 
      geojson = $.parseJSON(data); 



       L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { 
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', 
        maxZoom: 18, 
        id: 'mapbox.streets', 
        accessToken: 'ACCESS_TOKEN' 
       }).addTo(mymap); 

       //add external geojson to map 
      var cordinates = L.geoJSON(geojson).addTo(mymap); 

      //Add popups to markers 
      function onEachFeature(feature,layer){ 
       if (feature.properties && feature.properties.popupContent) { 
        layer.bindPopup(feature.properties.popupContent); 
       } 
      } 
      L.geoJSON(geojson, { onEachFeature: onEachFeature }).addTo(mymap); 


       //Adding custom markers to maps 
       var HospIcon = L.icon({ 
        iconUrl: '<%= asset_path('red_MarkerH.png') %>', 

        iconSize:  [20, 50], // size of the icon 
        shadowSize: [50, 64], // size of the shadow 
        iconAnchor: [22, 94], // point of the icon which will correspond to markers location 
        shadowAnchor: [4, 62], // the same for the shadow 
        popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor 
       }); 

       var Custom_marker = L.geoJSON(geojson, { 
        pointToLayer : function(feature,latlng){ 
         return L.marker(latlng, {icon: HospIcon}).addTo(mymap); 
        } 
       }); 
     } 


    }); 


    var popup = L.popup(); 

    function onMapClick(e) { 
     popup 
      .setLatLng(e.latlng) 
      .setContent("You clicked the map at " + e.latlng.toString()) 
      .openOn(mymap); 
    } 

    mymap.on('click', onMapClick); 

我該如何解決this.Any幫助將不勝感激。 This is what the maps look like,The blue markers are the default,the red markers are the custom markers

任何幫助將不勝感激,在此先感謝。

回答

1

因爲這個函數

var cordinates = L.geoJSON(geojson).addTo(mymap); 

將增加你的座標,並使用默認的標誌圖標,如果你想修改默認的標記,你應該在這個函數定義回調如下

my_json = L.geoJson(geojson, { 
    pointToLayer: function (feature, latlng) { 
     var smallIcon = new L.Icon({ 
      iconSize: [27, 27], 
      iconAnchor: [13, 27], 
      popupAnchor: [1, -24], 
      iconUrl: 'icone/chapel-2.png' 
     }); 
     return L.marker(latlng, {icon: smallIcon}); 
    } 
}); 

在你的情況,標記繪製兩次,因爲你從注入GeoJson的第一次渲染它兩次addTo(mymap)。第二,當你確定你的圖標並將其添加到您的地圖

引用:

+0

這是爲我工作,謝謝 –

+0

如果這個幫助你請註明作爲答案 – Vico

相關問題