本文說明如何在執行期間變更地圖樣式。
主要步驟為取得 BaseLayer,修訂樣式並且合併回 BaseLayer。
JavaScript
function changeFeatureStyle(map){
// 取得基礎圖層 BaseLayer
var provider = map.getBaseLayer().getProvider();
// 從 BaseLayer 取得樣式
var parkStyle = provider.getStyle();
var changeListener = (evt) => {
if (parkStyle.getState() === H.map.Style.State.READY) {
parkStyle.removeEventListener('change', changeListener);
// 查詢與配置地圖樣式
var parkConfig = parkStyle.extractConfig(['landuse.park', 'landuse.builtup']);
// 變更顏色
parkConfig.layers.landuse.park.draw.polygons.color = '#2ba815'
parkConfig.layers.landuse.builtup.draw.polygons.color = '#676d67'
// 將配置合併回 BaseLayer
parkStyle.mergeConfig(parkConfig);
}
};
parkStyle.addEventListener('change', changeListener);
}
/**
* map 初始化相關代碼:
*/
// Step 1: 初始化 platform
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: 初始化 map
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map, {
center: {lat:25.03746, lng:121.564558},
zoom: 13,
pixelRatio: window.devicePixelRatio || 1
});
// 加入 resize listener
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: 建立地圖互動性
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// 建立預設 UI 元件
var ui = H.ui.UI.createDefault(map, defaultLayers);
changeFeatureStyle(map);
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>在執行期間變更地圖樣式</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="../template.css" />
<script type="text/javascript" src='../test-credentials.js'></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
</head>
<body id="markers-on-the-map">
<div id="map"></div>
<script type="text/javascript" src='demo.js'></script>
</body>
</html>
CSS
#map {
width: 95%;
height: 450px;
background: grey;
}
#panel {
width: 100%;
height: 400px;
}
執行結果