Highmaps 从 1.1.0 开始支持经纬度定位功能,该功能依赖第三方库 proj4js(需要在 Highmaps 之前引入),最新版的文件可以从 cdnjs 上获取
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js"></script>
有了经纬度支持后,我们可以通过 lon
和 lat
属性来指定经纬度进行描点
series: [{
type: 'mappoint',
name: 'cities',
data: [{
name: '北京',
lat: 39.9032724643, // 经纬度查询请到 http://www.gpsspg.com/maps.htm
lon: 116.4009203787
},{
name: '杭州',
lon: 120.1551656314,
lat: 30.2741702308
}]
}]
中国主要城市经纬度数据
为了方便国内用户使用,我们将国内主要城市(338 个)的经纬度信息收集汇总并转换成 Highmaps 坐标值,最终的结果提供数据接口和文件下载,相关文件及调用方法如下:
- JSON 文件:https://data.jianshukeji.com/geochina/cities.json
- JS 文件:https://data.jianshukeji.com/geochina/cities.js
JSON 调用(JSONP)
$.getJSON('https://data.jianshukeji.com/jsonp?filename=geochina/cities.json&callback=?', function(cities) {
// ...
series: [{
type: 'mappoint',
name: 'cities',
data: [{
name: '北京',
x: cities['北京'].x, // 直接使用转换好的坐标轴
y: -cities['北京'].y,
}]
}]
})
JS 调用
<script src="https://data.jianshukeji.com/geochina/cities.js"></script>
<script>
var cities = Highcharts.map['china-cities'],
mappoint = Highcharts.geojson(cities, 'mappoint');
// ...
series: [{
type: 'mapbubble',
mapData: mappoint,
data: [{
name: '北京',
z: 1000
},{
name: '上海',
z: 800
}],
joinBy: 'name'
}]
</script>
经纬度转换
Highmaps 提供了 Chart.transformFromLatLon 和 Chart.transformToLatLon 这个两个函数用于经纬度值和 Highmaps 坐标轴进行互相转换。
如果不想依赖 Highmaps 直接进行经纬度转换,可以使用 proj4js
提供的函数进行转换,下面是简单的示例代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js"></script>
<script>
// Highmaps 默认的坐标系统参数
var transform = {
"crs": "+proj=lcc +lat_1=18 +lat_2=24 +lat_0=21 +lon_0=114 +x_0=500000 +y_0=500000 +ellps=WGS72 +towgs84=0,0,1.9,0,0,0.814,-0.38 +units=m +no_defs",
"scale": 0.000129831107685,
"jsonres": 15.5,
"jsonmarginX": -999,
"jsonmarginY": 9851.0,
"xoffset": -3139937.49309,
"yoffset": 4358972.7486
};
/**
* 经纬度转换函数
* @param float lon 经度
* @param float lat 纬度
* @return [x, y]
*/
function lonlatToXY(lon, lat) {
if(typeof lon === 'string') {
lon = parseFloat(lon);
}
if(typeof lat === 'string') {
lat = parseFloat(lat);
}
var projected = proj4(transform.crs, [lon, lat]),
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
rotated = transform.rotation ? [projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle] : projected;
return [
parseInt(((rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0)),
parseInt((((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0))
];
}
</script>