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

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

yuyutoo 2025-05-02 14:25 4 浏览 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文件同一目录下),添加标记功能、搜索标记功能、清楚标记功能、导出标记功能、加载标记功能。

相关推荐

对volatile,synchronized,AQS的加锁解锁原理的一些理解

一、为什么要加锁,要实现同步多线程编程中,有可能会出现多个线程同时访问同一个共享、可变资源的情况,这个资源我们称之其为临界资源;这种资源可能是:对象、变量、文件等。...

注意,不能错过的CAS+volatile实现同步代码块

前言:最近看到有人说可以使用CAS+volatile实现同步代码块。心想,确实是可以实现的呀!因为AbstractQueuedSynchronizer(简称AQS)内部就是通过CAS+...

面试并发volatile关键字时,我们应该具备哪些谈资?

提前发现更多精彩内容,请访问https://dayarch.top/提前发现更多精彩内容,请访问https://dayarch.top/提前发现更多精彩内容,请访问https://dayarch...

无锁同步-JAVA之Volatile、Atomic和CAS

1、概要本文是无锁同步系列文章的第二篇,主要探讨JAVA中的原子操作,以及如何进行无锁同步。关于JAVA中的原子操作,我们很容易想到的是Volatile变量、java.util.concurrent....

C/C++面试题(二):std::atomic与volatile

volatile是C/C++中的一个关键字,用于告知编译器某个变量的值可能会在程序的控制之外被意外修改(例如被硬件、中断服务程序、多线程环境或其他外部代理)。为了防止编译器对代码进行某些可能破坏...

VOCs(Volatile Organic Compounds)挥发性有机化合物及测试方法

经常看到一些三防漆、涂料、油漆类产品的介绍中提到VOC、VOCs等概念,那么什么是VOC、VOCs和TVOC,VOCs主要包括哪些物质?VOCs的来源有哪些?VOCs的危害及国家标准是什么?一、V...

对volatile 及happen—before的理解

happen—before规则介绍Java...

这一篇我们来了解Synchronized、Volatile、Final关键字

题外话:蓝银王觉醒了!!--来自于一个斗罗大陆动漫爱好者(鹅,打钱!)湿兄这两天回家了,办了点大事,回来的时候我弟弟还舍不得我,哭着不愿意让我回京(我弟还是小学),我也心里很不舍,但是还是要回京奋斗...

关于 Java 关键字 volatile 的总结

1什么是volatilevolatile是Java的一个关键字,它提供了一种轻量级的同步机制。相比于重量级锁synchronized,volatile更为轻量级,因为它不会引起线程上下文...

大白话聊聊Java并发面试问题之volatile到底是什么?

用最简单的大白话,加上多张图给大家说一下,volatile到底是什么?...

为什么要有volatile关键字(volatile 关键字为什么不能保证原子性)

在嵌入式编程和多线程编程中,我们常会见到volatile关键字声明的变量。下面说一下volatile关键字的作用:1.保持变量内存可见简而言之就是用volatile声明的变量会告诉编译器和处理器,这个...

Java的volatile到底怎么理解?(java volatitle)

我们都知道,在Java中有很多的关键字,比如synchronize比如volatile,这些都是一些比较关键的,还有final,今天我们就来聊一下这个volatile因为这个vo...

Java多线程编程中的volatile关键字:解密神秘的共享内存

Java多线程编程中的volatile关键字:解密神秘的共享内存在Java多线程编程的世界里,volatile关键字就像一位低调却至关重要的守护者。它默默无闻地站岗放哨,确保多个线程之间能够正确地共享...

你了解volatile关键字的作用吗?(关键字volatile有什么含意?并举出三个不同的例子?)

【死记硬背】volatile关键字主要用于保持内存的变量可见性和禁止重排序。变量可见性:当一个线程改变了变量的值,那么新的值对于其他线程也是可以立即获取到的。禁止重排序:...

谈谈你对volatile 关键字作用和原理的理解

一位6年工作经验的小伙伴,在某里二面的时候被问到“volatile”关键字。然后,就没有然后了…同样,还有一位4年的小伙伴,去某团面试也被问到“volatile关键字“。然后,也没有然后了…...

取消回复欢迎 发表评论: