百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

DeepSeek代码之旅1:卫星地图标记方法之——html语言的实现

yuyutoo 2025-05-02 14:25 29 浏览 0 评论

最近遇到一个任务,具体功能如下:

1、调用高德地图API,图层为卫星图层,根据需要标记兴趣点;

2、标记完成后可以保存兴趣点,便于下次加载历史兴趣点。

目前DeepSeek是非常的火爆啊,听说写代码还不错,那就赶紧把需求跟它说说吧,首先我们得告诉它使用什么语言去实现什么功能,我提问如下:

使用HTML语言,实现在线高德卫星地图api多点标记功能,具体实现如下:HTML界面中添加功能区、显示区。
1、功能区:靠左,文本框 1 显示“经度”、经度输入框 1(经度)(鼠标点击自动获取)、文本框 2 显示“纬度”、经度输入框 2(纬度)(鼠标点击自动获取)、标记点文本框显示“标记点名称”、标记点名称输入框,添加标记按钮、搜索标记按钮、清楚所有标记按钮、导出标记按钮、加载本地标记按钮;
2、显示区:靠右,显示地图

它直接给出了解决方案,并得到html代码示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>高德地图多点标记系统</title>
    <style>
        body { margin: 0; padding: 0; }
        #container {
            display: flex;
            height: 100vh;
        }
        #control-panel {
            width: 300px;
            padding: 20px;
            background: #f0f0f0;
            overflow-y: auto;
        }
        #map-container {
            flex: 1;
            height: 100%;
        }
        .input-group { margin-bottom: 15px; }
        input[type="text"] { width: 100%; padding: 5px; }
        button { padding: 8px 15px; margin: 5px; cursor: pointer; }
    </style>
</head>
<body>
    <div id="container">
        <!-- 功能区 -->
        <div id="control-panel">
            <div class="input-group">
                <label>经度:</label>
                <input type="text" id="longitude" placeholder="点击地图获取">
            </div>
            <div class="input-group">
                <label>纬度:</label>
                <input type="text" id="latitude" placeholder="点击地图获取">
            </div>
            <div class="input-group">
                <label>标记名称:</label>
                <input type="text" id="marker-name">
            </div>
            <button onclick="addMarker()">添加标记</button>
            <button onclick="searchMarker()">搜索标记</button>
            <button onclick="clearMarkers()">清除所有标记</button>
            <button onclick="exportMarkers()">导出标记</button>
            <button onclick="document.getElementById('file-input').click()">加载标记</button>
            <input type="file" id="file-input" style="display: none;">
        </div>

        <!-- 地图显示区 -->
        <div id="map-container"></div>
    </div>

    <!-- 高德地图API -->
    <script src="https://webapi.amap.com/maps?v=2.0&key=您的高德地图Key"></script>
    <script>
        let map = null;
        let markers = [];

        // 初始化地图
        function initMap() {
            map = new AMap.Map('map-container', {
                zoom: 12,
                center: [116.397428, 39.90923],
                layers: [new AMap.TileLayer.Satellite()]
            });

            // 地图点击事件
            map.on('click', function(e) {
                document.getElementById('longitude').value = e.lnglat.getLng();
                document.getElementById('latitude').value = e.lnglat.getLat();
            });
        }

        // 添加标记
        function addMarker() {
            const lng = parseFloat(document.getElementById('longitude').value);
            const lat = parseFloat(document.getElementById('latitude').value);
            const name = document.getElementById('marker-name').value;

            if (isNaN(lng) || isNaN(lat)) return;

            const marker = new AMap.Marker({
                position: [lng, lat],
                title: name,
                map: map
            });

            markers.push({
                name: name,
                lng: lng,
                lat: lat,
                marker: marker
            });
        }

        // 搜索标记
        function searchMarker() {
            const name = prompt("请输入要搜索的标记名称:");
            const target = markers.find(m => m.name === name);
            if (target) {
                map.setCenter([target.lng, target.lat]);
                map.setZoom(17);
            }
        }

        // 清除所有标记
        function clearMarkers() {
            markers.forEach(m => m.marker.setMap(null));
            markers = [];
        }

        // 导出标记
        function exportMarkers() {
            const data = JSON.stringify(markers.map(m => ({
                name: m.name,
                lng: m.lng,
                lat: m.lat
            })));
            
            const blob = new Blob([data], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'markers.json';
            a.click();
        }

        // 文件读取
        document.getElementById('file-input').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const reader = new FileReader();
            
            reader.onload = function(event) {
                const data = JSON.parse(event.target.result);
                data.forEach(item => {
                    document.getElementById('longitude').value = item.lng;
                    document.getElementById('latitude').value = item.lat;
                    document.getElementById('marker-name').value = item.name;
                    addMarker();
                });
            };
            
            reader.readAsText(file);
        });

        // 初始化
        window.onload = initMap;
    </script>
</body>
</html>

我们直接将代码复制到vscode中(没有可以安装)方便代码修改,直接浏览器打开肯定是异常的!浏览器打开如下:

要想正常使用地图功能,首先我们要去高德开放平台(https://lbs.amap.com/)申请权限,如下图中控制台中申请得到key和安全密钥(创建新应用—>添加key—>选择web端):

我们将得到的key替换掉html代码中的位置:

刷新后发现可以正常显示了,但是标记点无法显示,根据不断的调试和优化得到最终的html代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>地图标记点管理系统</title>
    <script src="https://webapi.amap.com/loader.js"></script>
    <style>
        /* 页面布局 */
        body {
            display: flex;
            margin: 0;
            height: 100vh;
            font-family: Arial, sans-serif;
        }

        /* 功能区样式 */
        #function-area {
            width: 300px;
            padding: 20px;
            background-color: #f4f4f4;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            overflow-y: auto;
        }

        /* 显示区样式 */
        #display-area {
            flex: 1;
            position: relative;
        }

        /* 输入框和按钮样式 */
        .input-group {
            margin-bottom: 15px;
        }

        input[type="text"], button {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }

        #coordinates {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: white;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            z-index: 999;
        }
        /* 新增文件上传样式 */
        .file-input {
            display: none;
        }
        .file-upload-label {
            display: block;
            text-align: center;
            padding: 8px;
            background: #28a745;
            color: white;
            border-radius: 4px;
            cursor: pointer;
        }
        .file-upload-label:hover {
            background: #218838;
        }

    </style>
</head>
<body>
    <!-- 功能区 -->
    <div id="function-area">
        <div class="input-group">
            <label>经度</label>
            <input type="text" id="longitude" placeholder="点击地图获取或输入">
        </div>
        
        <div class="input-group">
            <label>纬度</label>
            <input type="text" id="latitude" placeholder="点击地图获取或输入">
        </div>

        <div class="input-group">
            <label>标记名称</label>
            <input type="text" id="marker-name" placeholder="输入标记点名称">
        </div>
        <button id="add-marker">添加标记</button>
        <button id="search-marker">搜索标记</button>
        <button id="clear-markers">清除所有标记</button>
        <button id="export-data">导出数据</button>
        <!-- 新增文件上传组件 -->
        <input type="file" id="file-input" class="file-input" accept=".json">
        <label for="file-input" class="file-upload-label">导入JSON文件</label>
     </div>

    <!-- 地图显示区 -->
    <div id="display-area">
        <div id="mapContainer" style="width:100%;height:100%;"></div>
        <div id="coordinates">点击地图获取坐标:未记录</div>
    </div>

<script>
// 高德地图初始化
let map;
let markers = [];
const AMapKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 替换为真实Key

// 页面元素
const longitudeInput = document.getElementById('longitude');
const latitudeInput = document.getElementById('latitude');
const markerNameInput = document.getElementById('marker-name');

// 初始化地图
window.onload = function() {
    AMapLoader.load({
        key: AMapKey,
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.ToolBar']
    }).then((AMap) => {
        map = new AMap.Map('mapContainer', {
            layers: [new AMap.TileLayer.Satellite()],
            zoom: 13,
            center: [108.378925, 22.842527]
        });
        
        // 添加控件
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.ToolBar());

        // 地图点击事件
        map.on('click', function(e) {
            const lng = e.lnglat.getLng().toFixed(6);
            const lat = e.lnglat.getLat().toFixed(6);
            longitudeInput.value = lng;
            latitudeInput.value = lat;
            document.getElementById('coordinates').innerHTML = 
                `点击坐标:经度 ${lng}, 纬度 ${lat}`;
        });
    });
};

// 添加标记函数
function addMarker(lng, lat, title) {
    if (!map) return;
    // 获取当前页面的URL
    var currentURL = window.location.href;
    // 提取目录路径
    var directoryPath = currentURL.substring(0, currentURL.lastIndexOf('/') + 1);
    // 将目录路径显示在页面上
    document.getElementById('coordinates').textContent = "当前目录: " + directoryPath;
    const marker = new AMap.Marker({
        position: [parseFloat(lng), parseFloat(lat)],
        map: map,
        title: title,
        icon: directoryPath + "towerdot.png"
    });
    // 信息窗口
    marker.on('click', () => {
        new AMap.InfoWindow({
            content: `<strong>${title}</strong><br>经纬度:${lng},${lat}`
        }).open(map, marker.getPosition());
    });

    markers.push(marker);
}
// NEW: 添加文件导入功能
document.getElementById('file-input').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(event) {
        try {
            const importedData = JSON.parse(event.target.result);
            
            // 验证数据格式
            if (!Array.isArray(importedData)) {
                throw new Error("无效的JSON格式");
            }

            importedData.forEach(marker => {
                if (!marker.lng || !marker.lat || !marker.title) {
                    throw new Error("缺少必要字段: lng/lat/title");
                }
                addMarker(marker.lng, marker.lat, marker.title);
            });
        } catch (error) {
            alert(`导入失败: ${error.message}`);
        }
    };
    reader.readAsText(file);
});
// 事件监听
document.getElementById('add-marker').addEventListener('click', () => {
    const lng = longitudeInput.value;
    const lat = latitudeInput.value;
    const title = markerNameInput.value;

    if (!lng || !lat) return alert("请先获取或输入坐标!");
    if (!title) return alert("请输入标记名称!");
    
    addMarker(lng, lat, title);
    markerNameInput.value = ''; // 清空名称输入
});

document.getElementById('search-marker').addEventListener('click', () => {
    const keyword = prompt("请输入搜索关键词:");
    if (!keyword) return;

    const found = markers.find(marker => 
        marker.getTitle().includes(keyword)
    );

    if (found) {
        map.setCenter(found.getPosition());
        map.setZoom(16);
        found.emit('click'); // 触发点击显示信息窗口
    } else {
        alert("未找到匹配标记!");
    }
});

document.getElementById('clear-markers').addEventListener('click', () => {
    markers.forEach(marker => marker.setMap(null));
    markers = [];
    alert("已清除所有标记!");
});

document.getElementById('export-data').addEventListener('click', () => {
    const data = markers.map(marker => ({
        lng: marker.getPosition().lng,
        lat: marker.getPosition().lat,
        title: marker.getTitle()
    }));
    
    const blob = new Blob([JSON.stringify(data)], {type: 'application/json'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'markers.json';
    a.click();
});
</script>
</body>
</html>

复制上面代码保存为html文件,并将上面代码中AMapKey替换为自己的key后可以得到如下界面:

最终实现:自定义标记点图标(图标文件需与html文件同一目录下),添加标记功能、搜索标记功能、清楚标记功能、导出标记功能、加载标记功能。

相关推荐

《保卫萝卜2》安卓版大更新 壕礼助阵世界杯

《保卫萝卜2:极地冒险》本周不仅迎来了安卓版本的重大更新,同时将于7月4日本周五,带来“保卫萝卜2”安卓版本世界杯主题活动的火热开启,游戏更新与活动两不误。一定有玩家会问,激萌塔防到底进行了哪些更新?...

儿童手工折纸:胡萝卜,和孩子一起边玩边学carrot

1、准备两张正方形纸,一橙一绿,对折出折痕。2、橙色沿其中一条对角线如图折两三角形。3、把上面三角折平,如图。4、绿色纸折成三角形。5、再折成更小的三角形。6、再折三分之一如图。7、打开折纸,压平中间...

《饥荒》食物代码有哪些(饥荒最新版代码总汇食物篇)

饥荒游戏中,玩家们需要获取各种素材与食物,进行生存。玩家们在游戏中,进入游戏后按“~”键调出控制台使用代码,可以直接获得素材。比如胡萝卜的代码是carrot,玉米的代码是corn,南瓜的代码是pump...

Skyscanner:帮你找到最便宜机票 订票不求人

你喜欢旅行吗?在合适的时间、合适的目的地,来一场说走就走的旅行?机票就是关键!Skyscanner这款免费的手机应用,在几秒钟内比较全球600多家航空公司的航班安排、价格和时刻表,帮你节省金钱和时间。...

小猪佩奇第二季50(小猪佩奇第二季英文版免费观看)

Sleepover过夜Itisnighttime.现在是晚上。...

我在民政局工作的那些事儿(二)(我在民政局上班)

时间到了1997年的秋天,经过一年多的学习和实践,我在处理结婚和离婚的事情更加的娴熟,也获得了领导的器重,所以我在处理平时的工作时也能得心应手。这一天我正在离婚处和同事闲聊,因为离婚处几天也遇不到人,...

夏天来了就你还没瘦?教你不节食13天瘦10斤的哥本哈根减肥法……

好看的人都关注江苏气象啦夏天很快就要来了你是否和苏苏一样身上的肉肉还没做好准备?真是一个悲伤的故事……下面这个哥本哈根减肥法苏苏的同事亲测有效不节食不运动不反弹大家快来一起试试看吧~DAY1...

Pursuing global modernization for peaceful development, mutually beneficial cooperation, prosperity for all

AlocalworkeroperatesequipmentintheChina-EgyptTEDASuezEconomicandTradeCooperationZonei...

Centuries-old tea road regains glory as Belt and Road cooperation deepens

FUZHOU/ST.PETERSBURG,Oct.2(Xinhua)--NestledinthepicturesqueWuyiMountainsinsoutheastChi...

15 THE NUTCRACKERS OF NUTCRACKER LODGE (CONTINUED)胡桃夹子小屋里的胡桃夹子(续篇)

...

AI模型部署:Triton Inference Server模型部署框架简介和快速实践

关键词:...

Ftrace function graph简介(flat function)

引言由于android开发的需要与systrace的普及,现在大家在进行性能与功耗分析时候,经常会用到systrace跟pefetto.而systrace就是基于内核的eventtracing来实...

JAVA历史版本(java各版本)

JAVA发展1.1996年1月23日JDK1.0Java虚拟机SunClassicVM,Applet,AWT2.1997年2月19日JDK1.1JAR文件格式,JDBC,JavaBea...

java 进化史1(java的进阶之路)

java从1996年1月第一个版本诞生,到2022年3月最新的java18,已经经历了27年,整整18个大的版本。很久之前有人就说java要被淘汰,但是java活到现在依然坚挺,不知道java还能活...

学习java第二天(java学完后能做什么)

#java知识#...

取消回复欢迎 发表评论: