使用queryRenderedFeatures API来显示地图元素上的鼠标悬停位置特性
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
#features {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 300px;
overflow: auto;
background: rgba(255, 255, 255, 0.8);
}
#map canvas {
cursor: crosshair;
}
</style>
<div id='map'></div>
<pre id='features'></pre>
<script>
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-96, 37.8],
zoom: 3
});
map.on('mousemove', function (e) {
var features = map.queryRenderedFeatures(e.point);
document.getElementById('features').innerHTML = JSON.stringify(features, null, 2);/* JSON.stringify(value[, replacer [, space]]):JSON.stringify() 方法可以将任意的 JavaScript 值序列化成 JSON 字符串。若转换的函数被指定,则被序列化的值的每个属性都会经过该函数的转换和处理;若转换的数组被指定,只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中。value
将要序列化成 JSON 字符串的值。
replacer 可选
如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;
如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;
如果该参数为null或者未提供,则对象所有的属性都会被序列化;
关于该参数更详细的解释和示例,请参考使用原生的 JSON 对象一文。
space 可选
指定缩进用的空白字符串,用于美化输出(pretty-print);
如果参数是个数字,它代表有多少的空格;上限为10。改值若小于1,则意味着没有空格;
如果该参数为字符串(字符串的前十个字母),该字符串将被作为空格;
如果该参数没有提供(或者为null)将没有空格。 */
});
</script>
</body>
</html>