高德地图通过GPS经纬度获取附近的地名


(function() {
    'use strict';
    function addBtn(){
        // 选择目标 DOM 节点
        const targetNode = document.querySelector("#mtCase > div.row > div > div > div > div:nth-child(1)");

        // 检查目标节点是否存在
        if (targetNode) {
            // 创建一个 button 元素
            const button = document.createElement("button");

            // 设置按钮的文字内容
            button.textContent = "获取地名";
            button.style.display="block"
            // 为按钮添加点击事件
            button.addEventListener("click", function () {
                doSomething()
            });

            // 将按钮添加到目标节点中
            targetNode.appendChild(button);
        } else {
            console.error("目标节点未找到!");
        }
    }
    function copyText(textToCopy){
        // 创建一个临时的 textarea 元素
        const tempTextArea = document.createElement("textarea");
        tempTextArea.value = textToCopy;

        // 将临时元素添加到文档中(不可见)
        document.body.appendChild(tempTextArea);

        // 选中临时元素中的文本
        tempTextArea.select();
        tempTextArea.setSelectionRange(0, 99999); // 对于移动设备的支持

        try {
            // 执行复制命令
            document.execCommand("copy");
            alert("地名已复制到剪贴板!");
        } catch (err) {
            console.error("复制失败:", err);
            alert("地名复制失败,请重试!");
        }

        // 移除临时元素
        document.body.removeChild(tempTextArea);
    }
    function doSomething(){
        let GPS1Dom = document.querySelector("#mtCase > div.row > div > div > div > div:nth-child(1) > span:nth-child(2)")
        let GPS2dom = document.querySelector("#mtCase > div.row > div > div > div > div:nth-child(1) > span:nth-child(3)")
        let GPS1 = GPS1Dom.textContent.split(":")[1]
        let GPS2 = GPS2dom.textContent.split(":")[1]
        fetchRegeo(GPS1).then(data => {
            //console.log("完整地址:", data.regeocode.formatted_address);
            let addressName1 = data.regeocode.formatted_address
            fetchRegeo(GPS2).then(data => {
                //console.log("完整地址:", data.regeocode.formatted_address);
                let addressName2 = data.regeocode.formatted_address
                copyText(`起点:${addressName1}\n终点:${addressName2}`)
            })
                .catch(error => {
                console.error("发生错误:", error.message);
            });
        })
            .catch(error => {
            console.error("发生错误:", error.message);
        });
    }
    function fetchRegeo(locations) {
        const apiKey = 'xxxxxx';
        const url = `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${locations}&key=${apiKey}&radius=500&extensions=all`;
        // 返回一个 Promise 对象
        return new Promise((resolve, reject) => {
            fetch(url)
                .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json(); // 解析 JSON 数据
            })
                .then(data => {
                if (data.status === "1" && data.info === "OK") {
                    resolve(data); // 成功时返回数据
                } else {
                    reject(new Error(`API error: ${data.infocode}, ${data.info}`));
                }
            })
                .catch(error => {
                reject(error); // 捕获错误并传递给 reject
            });
        });
    }
    // 创建一个 MutationObserver 实例
    const observer = new MutationObserver(function (mutationsList) {
        // 检查目标节点是否存在
        const targetNode = document.querySelector("#mtCase > div.row > div > div > div > div:nth-child(1)");
        if (targetNode) {
            addBtn(); // 如果目标节点存在,调用 addBtn 函数
            observer.disconnect(); // 停止观察
        }
    });

    // 开始监听 DOM 变化
    observer.observe(document.body, { childList: true, subtree: true });
})();

posted @ 2025-04-14 11:40  lambertlt  阅读(43)  评论(0)    收藏  举报