You need to enable JavaScript to run this app. OpenLayers如何将MousePosition控件的坐标格式修改为HDMS格式
优惠活动
大模型
产品
解决方案
定价
更多

OpenLayers如何将MousePosition控件的坐标格式修改为HDMS格式

OpenLayers MousePosition控件输出HDMS格式坐标解决方案

问题原因

你调用ol.coordinate.toStringHDMS()时额外加了括号,相当于没有传入坐标参数就立即执行了该方法,自然无法得到预期的格式化结果。coordinateFormat参数需要接收的是坐标格式化函数的引用,控件会在鼠标移动时自动将当前坐标作为参数传入该函数执行。

正确实现代码

基础HDMS格式输出

var mouseposition = new ol.control.MousePosition({
    projection: 'EPSG:4326',
    coordinateFormat: ol.coordinate.toStringHDMS, // 直接传函数引用,不要加括号
    undefinedHTML: '',
    className: 'ol-mouse-position ol-control'
});
map.addControl(mouseposition);

自定义精度的HDMS格式输出

如果需要调整秒数的小数保留位数,可以使用ol.coordinate.createStringHDMS方法自定义格式化规则:

var mouseposition = new ol.control.MousePosition({
    projection: 'EPSG:4326',
    // 两个参数分别对应分数的小数位数、秒数的小数位数,示例为秒数保留1位小数
    coordinateFormat: ol.coordinate.createStringHDMS(0, 1),
    undefinedHTML: '',
    className: 'ol-mouse-position ol-control'
});
map.addControl(mouseposition);

内容的提问来源于stack exchange,提问作者Yuri Furtado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 11:24:03