search
HomeWeb Front-endJS TutorialExtracting the longitude and latitude coordinates of administrative region boundaries from Amap and Baidu maps based on JavaScript

基于JavaScript实现高德地图和百度地图提取行政区边界经纬度坐标_javascript技巧

前言

近来由于工作需要,需要提取某些城市的经纬度坐标,稍微搜索了一下,发现百度地图和高德地图都提供了相关的函数和例子.那么剩余的工作也就比较简单了,保存坐标,然后转换为WGS坐标,这样才能和现有的GPS数据以及地图匹配.

主要问题和解决方法

本地保存文件跨浏览器支持

由于安全的原因,JavaScript本地保存文件的方式通常都只有IE支持的ActiveXObject/Open方法,每次都要提示不安全和允许运行,非常麻烦.好在其他浏览器目前都支持标签实现文件下载的方法.经测试最新的Google Chrome, Mozilla Firefox,百度浏览器,360浏览器下都可以运行.不说废话,直接上代码:


function Download() {
// IE
if(/msie/i.test(navigator.userAgent)) {
var w = window.open("", "导出", "height=0,width=0,toolbar=no,menubar=no,scrollbars=no,resizable=on,location=no,status=no");
var filename = document.getElementById("filename").value ;
var content = document.getElementById("content").value;
w.document.charset = "UTF-8";
w.document.write(content);
w.document.execCommand("SaveAs", false, filename+'.txt');
w.close();
}
// Firefox/Chrome/Safari/Opera
else {
var filename = document.getElementById("filename").value ;
var content = document.getElementById("content").value;
str = encodeURIComponent(content); 
document.getElementById("SaveChrome").download = filename+'.txt'; 
var aLink = document.getElementById("SaveChrome") ; 
aLink.href = "data:text/csv;charset=utf-8,"+str; 
aLink.click(); 
}
}

经纬度转换

这个话题感兴趣的朋友可以自己搜索火星坐标相关转换,精度在1m范围的网上提供有服务可以免费使用.自写程序经验证精度在6m 以内.

百度地图方法

关键函数是 BMap.Boundary() 生成的类,调用它的方法get就可以通过名称获得县或市级以上的行政区域.


function getBoundary() {
var bdary = new BMap.Boundary();
var name = document.getElementById("districtName").value;
bdary.get(name, function (rs) { //获取行政区域
var fileName = "";
var newFileObject = fso.CreateTextFile(folderName + "\\" + name + ".txt", true);
map.clearOverlays(); //清除地图覆盖物
var count = rs.boundaries.length; //行政区域的点有多少个
for (var i = 0; i < count; i++) {
var ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: "#ff0000" }); //建立多边形覆盖物
map.addOverlay(ply); //添加覆盖物
map.setViewport(ply.getPath()); //调整视野
}
newFileObject.write(rs.boundaries[0]);
newFileObject.Close();
});
}

高德地图

关键代码通过阅读示例文件可以发现在下拉列表返回里面有边界值的出现.


amapAdcode.search = function(adcodeLevel, keyword, selectId) {//查询行政区划列表并生成相应的下拉列表
var me = this;
if (adcodeLevel == &#39;district&#39;||adcodeLevel == &#39;city&#39;) {//第三级时查询边界点
this._district.setExtensions(&#39;all&#39;);
} else {
this._district.setExtensions(&#39;base&#39;);
}
this._district.setLevel(adcodeLevel); //行政区级别
this._district.search(keyword, function(status, result) {//注意,api返回的格式不统一,在下面用三个条件分别处理
var districtData = result.districtList[0];
if (districtData.districtList) {
me.createSelectList(selectId, districtData.districtList);
} else if (districtData.districts) {
me.createSelectList(selectId, districtData.districts);
} else {
document.getElementById(selectId).innerHTML = &#39;&#39;;
}
map.setCenter(districtData.center);
me.clearMap();
me.addPolygon(districtData.boundaries);

其中的districtData.boundaries 就是我们需要的.调试了一下,大胆猜测果然是实现了Tostring() 方法的一个对象.
"104.639106,26.863388,104.644771,26.861842,104.64767,26.854997,104.647748..." 很明显的就是我们需要的gcj坐标.

总结

至此,基本也就没有什么问题了,剩余的工作就是解析得到的文件.需要提取全国的数据也就是循环读取全国城市列表文件了.(通常搜索cityname,电脑里面都会找到的,原因,呵呵,猜测是迅雷,QQ之类的IP定位需要吧.)

重要的一点,推荐使用高德地图,原因就是百度地图得到的行政规划有问题,不包含县级市.最典型的就是贵州省,很多地市都是分离的,是带岛或洞的复杂多边形.百度在这里完败.关于怎么处理这里复杂的多边形以支持在MapWinGIS显示和处理,下次会写一篇笔记.

以上就是基于JavaScript实现高德地图和百度地图提取行政区边界经纬度坐标_javascript技巧的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools