Vue3集成Leaflet搜索框报错:L.Control.Search.callJsonp不是函数
解决Vue3中Leaflet Search的搜索错误问题
问题分析
你遇到两个核心问题:
- 搜索请求的
q参数被错误替换为[object Object],导致请求无效 L.Control.Search.callJsonp is not a function报错,说明Leaflet Search的JSONP机制在Vue3的ES模块环境下无法正常工作
解决方案
1. 改用自定义数据源(替换JSONP)
放弃Leaflet Search自带的URL+JSONP模式,通过sourceData函数手动处理搜索请求,彻底规避JSONP的兼容性问题:
new L.Control.Search({ // 自定义搜索数据源处理逻辑 sourceData: function(query, callback) { // 用Fetch API请求Nominatim接口,对搜索关键词编码避免请求异常 fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5`) .then(res => res.json()) .then(data => { // 将Nominatim返回的数据格式转为Leaflet Search可识别的结构 const formattedResult = data.map(item => ({ name: item.display_name, loc: [parseFloat(item.lat), parseFloat(item.lon)] })); // 把格式化后的数据传给搜索控件 callback(formattedResult); }) .catch(err => console.error('搜索请求失败:', err)); }, // 指定搜索结果中显示名称的字段 propertyName: 'name', // 指定搜索结果中存储坐标的字段 propertyLoc: 'loc', marker: L.circleMarker([0, 0], { radius: 30 }), autoCollapse: true, autoType: false, minLength: 2 }).addTo(this.map);
2. 解决跨域(CORS)问题
如果localhost环境下请求Nominatim出现跨域错误,在Vue项目中配置代理:
- 在项目根目录创建
vue.config.js(无则新建),添加以下配置:
module.exports = { devServer: { proxy: { '/nominatim': { target: 'https://nominatim.openstreetmap.org', changeOrigin: true, pathRewrite: { '^/nominatim': '' } } } } };
- 修改
sourceData中的请求地址为代理路径:
fetch(`/nominatim/search?format=json&q=${encodeURIComponent(query)}&limit=5`)
3. 确认版本兼容性
确保leaflet-search版本与Leaflet 1.9.3兼容,建议安装最新稳定版:
npm install leaflet-search@latest
内容的提问来源于stack exchange,提问作者DoDr
相关产品推荐
相关产品推荐

