使用Leaflet.js创建自定义标记在地图上添加多个标记
问题描述:
我正在编写一个应用程序,并且试图使用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 © <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
任何帮助将不胜感激,在此先感谢。
答
因为这个函数
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)
。第二,当你确定你的图标并将其添加到您的地图
引用:
这是为我工作,谢谢 –
如果这个帮助你请注明作为答案 – Vico