Reputation: 27
I'm writing an app and i'm trying to add custom markers using Leaflet.js .The code so far worked, and add custom markers to the map successfully, however the default markers exist too on the map.
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);
How can i solve this.Any help will be highly appreciated.This is what the maps look like,The blue markers are the default,the red markers are the custom markers
Any help will be highly appreciated,Thanks in Advance.
Upvotes: 0
Views: 4233
Reputation: 118
Because this function
var cordinates = L.geoJSON(geojson).addTo(mymap);
will add your coordinates and use default markers icon, if you want to modify the default marker, you should define callback in that function as below
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});
}
});
in your case, marker drawn twice because you render it twice addTo(mymap)
, from the first you inject GeoJson. And second, when you define your icons and add it to your map
references :
Upvotes: 2