
OpenStreetMap + Leafletで設置したマーカーにクリックのイベントを追加したの記事で、地図上に配置したマーカーにクリックイベントを設けた。

今回は地図上にもう一つマーカーを設置してみることにする。
前回の記事のマーカーの設置に関する箇所のコードをピックアップしてみる。
var feature = {
"type" : "Feature",
"properties" : {
"name" : "摂津峡",
"url" : "https://goo.gl/maps/pF6ukpbgf5tLBtTb7" // ←Google Mapsでの摂津峡の共有リンクの短縮版
},
"geometry" : {
"type": "Point",
"coordinates" : [lng, lat] //注意:緯度経度の渡し方が逆になる
}
};
L.geoJSON(feature, {
onEachFeature: function(features, layer) {
if (features.properties && features.properties.url) {
layer.on('click', function(ele) { //PCでマーカーをクリック
location.href = features.properties.url;
});
layer.on('tap', function(ele) { //スマホでマーカーをタップ
location.href= features.properties.url;
});
}
}
}).addTo(map);
このコードでL.getJSONの第一引数に位置情報に関するオブジェクトが一つに対して、第二引数で繰り返しの処理になっている事に違和感を感じると前回の記事で記載した。
このコードに対して、下記のように変更してみる。
var features = [
{
"type":"Feature",
"properties":{
"name":"摂津峡",
"url":"https://goo.gl/maps/pF6ukpbgf5tLBtTb7"
},
"geometry": {
"type": "Point",
"coordinates":[135.58724326280114, 34.877647854266584] //注意:緯度経度の渡し方が逆になる
}
},
{
"type":"Feature",
"properties":{
"name":"山水館",
"url":"https://goo.gl/maps/eresbZ5H4gJBajRV8"
},
"geometry": {
"type": "Point",
"coordinates":[135.5864828823669, 34.878894143428354] //注意:緯度経度の渡し方が逆になる
}
}
];
L.geoJSON(features, {
onEachFeature: function(features, layer) {
if (features.properties && features.properties.url) {
layer.on('click', function(ele) { //PCでマーカーをクリック
location.href = features.properties.url;
});
layer.on('tap', function(ele) { //スマホでマーカーをタップ
location.href= features.properties.url;
});
}
}
}).addTo(map);
※地図の中心の緯度経度も変更しているが、今回は省略する。
位置情報のオブジェクトを複数持てるように配列型の変数にして、L.getJSONの第一引数で位置情報の配列を渡す。
上記の変更後にブラウザを介してファイルを実行してみると、

複数のマーカーが設置された状態で地図が表示された。
マーカーの設置個数を増やしたい場合はfeaturesの値を増やすだけで良い。





