Mapbox GL データの内容により、マーカーの色を変更する

Javascript

下記のMapbox GLのStyleの仕様を見ていると、サークルでpaintするマーカーの色を変更する、など簡単!にできそうですが、これがあまり素直なつくりではありません。

https://www.mapbox.com/mapbox-gl-style-spec/#paint-circle-radius

ここでマーカーの色がもともと決めてあり、マーカーにより変更したい場合があります。

配送先A:赤
配送先B:青

みたいな感じですね。

下記の情報が大変参考になります。
Mapbox GL data-driven style reference

まず、配送先IDと色のキー:バリューの配列を作って、colorListに入れます。

 var colorList =  [
                   ["128", "#ff0000"], 
                   ["107", "#0d3afc"], 
                   ["1", "#00FF00"]
                  ];

GeoJSONを次のように作っておきます。

 var destinations = [

{type:”Feature”, geometry:{type:”Point”,
coordinates:[139.5920549, 35.4558924]},
properties:{id:”128″,
name:”配送先A”,
color:”#333333″,
information:”hogehoge”,
url:”/destination/viewDestination&destination_id=128&company_id=9841″
}
},
{type:”Feature”, geometry:{type:”Point”,
coordinates:[136.62946120000004, 36.5974896]},
properties:{id:”107″,
name:”配送先B”,
   color:”#333333″,

                                                     information:"", 
                                                     url:"/destination/viewDestination&destination_id=107&company_id=9841"
                                                    }
                        }
                 ]

そして、地図にスタイルを追加するときに、次のようにします。

 	map.on('style.load', function() {
 
 		map.addSource("destinations", {
 			"type" : "geojson",
 			"data" : {
 				"type" : "FeatureCollection",
 				"features" : destinations
 
 			}
 		});
 
 		map.addLayer({
 			"id" : "destinations",
 			"type" : "circle",
 		     "source": "destinations",
 		     "paint": {
 		    	'circle-stroke-color' : "#f5f0f0",
 		    	'circle-stroke-width' : 2,
                 'circle-radius': 12,
                'circle-color':  { 
                   //ここがポイント これで、idでcolorListから色を引いて
                   //ペイントできる
                    "property": "id",
                    "type": "categorical",
                    "stops": colorList                            
                }
            },
 		}, 'destinations_symbol');
 		
 		map.addLayer({
 			"id" : "destinations_symbol",
 			"type" : "symbol",
 			"source" : "destinations",
 			"layout" : {
 				"icon-image" : "building-15",
 				"text-field" : "{name}",
 				"text-font" : [ "Open Sans Semibold",
 						"Arial Unicode MS Bold" ],
 				"text-offset" : [ 0, 1 ],
 				"text-size" : 13,
 				"text-anchor" : "top"
 			},
             "paint": {
                "text-color": "#023295",
                "text-halo-color" : "#ffffff",
                "text-halo-width" : 2
            },
 		});

ちなみに上記のサンプルは、サークルの上にマーカーを表示しています。

下記の図のようになります。

map_color_circle.png

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です