如何从XML文件生成JavaScript数组/对象适配Google Maps API v3
XML标记数据转指定JavaScript数组的可行方案
方案一:前端JavaScript直接解析XML(修复XMLHttpRequest问题)
你之前尝试XMLHttpRequest失败,大概率是XML解析环节出错,以下是完整可运行的代码:
// 初始化目标数组 const marqueurCanonTest4 = []; // 创建并发送XML请求 const xhr = new XMLHttpRequest(); xhr.open('GET', 'markers.xml', true); // 替换为你的XML文件实际路径 xhr.onload = function() { if (this.status === 200) { // 解析XML响应文档 const xmlDoc = this.responseXML; // 获取所有<marker>元素 const markerElements = xmlDoc.getElementsByTagName('marker'); // 遍历每个marker,转换为目标结构 for (let i = 0; i < markerElements.length; i++) { const elem = markerElements[i]; marqueurCanonTest4.push({ latitudeCanon: elem.getAttribute('lat'), longitudeCanon: elem.getAttribute('lng'), nomCanon: elem.getAttribute('name'), categorieCanon: elem.getAttribute('category'), nationCanon: elem.getAttribute('nation'), typeCanon: elem.getAttribute('typecanon'), lieuCanon: elem.getAttribute('lieu'), paysCanon: elem.getAttribute('pays'), url: elem.getAttribute('url') }); } // 转换完成,可用于Google Maps v3标记加载 console.log('转换后的数组:', marqueurCanonTest4); } else { console.error('XML加载失败,状态码:', this.status); } }; xhr.onerror = function() { console.error('请求XML文件时发生网络错误'); }; xhr.send();
关键注意事项
- 确保XML文件与当前页面同域,否则会触发跨域限制;若跨域需后端配置CORS,或改用后端中转方案
- 确认XML文件编码为UTF-8,避免特殊字符乱码
方案二:后端PHP中转(适配你的技术栈,更简便)
鉴于你熟悉PHP,推荐先在后端将XML转换为JSON,前端直接请求JSON数据,避免XML解析的繁琐:
后端PHP代码(xml-to-json.php)
<?php // 加载XML文件 $xml = simplexml_load_file('markers.xml'); $markerList = []; // 遍历所有marker节点,转换为目标结构 foreach ($xml->marker as $marker) { $attrs = $marker->attributes(); $markerList[] = [ 'latitudeCanon' => (string)$attrs->lat, 'longitudeCanon' => (string)$attrs->lng, 'nomCanon' => (string)$attrs->name, 'categorieCanon' => (string)$attrs->category, 'nationCanon' => (string)$attrs->nation, 'typeCanon' => (string)$attrs->typecanon, 'lieuCanon' => (string)$attrs->lieu, 'paysCanon' => (string)$attrs->pays, 'url' => (string)$attrs->url ]; } // 输出JSON格式数据 header('Content-Type: application/json; charset=utf-8'); echo json_encode($markerList); ?>
前端请求JSON的代码
const marqueurCanonTest4 = []; // 使用fetch API(也可继续用XMLHttpRequest) fetch('xml-to-json.php') .then(res => { if (!res.ok) throw new Error('数据请求失败'); return res.json(); }) .then(data => { // 将JSON数据直接赋值到目标数组 marqueurCanonTest4.push(...data); console.log('转换后的数组:', marqueurCanonTest4); // 此处可调用Google Maps v3的标记添加逻辑 }) .catch(err => console.error('加载失败:', err));
验证方式
转换完成后,打开浏览器控制台(F12),查看marqueurCanonTest4的输出,确认结构与你提供的目标格式一致即可。
内容的提问来源于stack exchange,提问作者bernard1418
相关产品推荐
相关产品推荐

