Home Web Front-end JS Tutorial How to calculate the driving distance between two places based on Baidu map (two languages ​​​​js and C#)_javascript skills

How to calculate the driving distance between two places based on Baidu map (two languages ​​​​js and C#)_javascript skills

May 16, 2016 pm 03:34 PM

The following is the use of js code to implement Baidu Map to calculate the distance between two places. The code is as follows:

<script src="js/jquery-1.9.0.js" type="text/javascript" language="javascript"></script>
<script language="javascript" type="text/javascript" src="js/area.js"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api&#63;v=1.2" language="javascript"></script>
</head>
<body>
  <div>
  <table border="0" align="center" cellpadding="0" cellspacing="0" class="w1000">
 <tr>
 <td>
  <td valign="top">
  <table width="1000px" border="0" cellspacing="0" cellpadding="0">
   <tr>
<td>
  <table width="1000px" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td width="19"><span style="padding-top: 2px;"></span></td>                      
                        <td width="60" style="font-size: 12px;">
                          出发城市                        </td>
                        <td>
                          <select id="AreaDept1_Province" style="width: 65px" onChange="changearea(this.value,document.getElementById('AreaDept1_Prefecture'));"
                            name="Area">
                            <option value="">-省份-</option>
                          </select>
                          <select id="AreaDept1_Prefecture" style="width: 65px" name="City" onchange="changecity(document.getElementById('AreaDept1_Province').value,document.getElementById('AreaDept1_Prefecture').value,document.getElementById('AreaDept1_Xian'))">
                            <option value="">-城市-</option>
                          </select>
                           <select id="AreaDept1_Xian" style="width: 65px" name="City">
                            <option value="">-县-</option>
                          </select>
                          <script language="JavaScript" type="text/javascript">
                            setup(document.getElementById("AreaDept1_Province"));
                            //$("#AreaDept1_Province").find("option[text='"+DProvice+"']").attr("selected",true);
                            //changearea(DProvice,document.getElementById('AreaDept1_Prefecture'));
                            //$("#AreaDept1_Prefecture").find("option[text='"+DCity+"']").attr("selected",true);
                          </script>                       </td>
                        <td width="26" align="center" style="font-size: 12px;">
                          到                        </td>
                        <td>
                          <select name="mdd" id="mdd" style="width: 65px" onChange="changearea(this.value,document.getElementById('cdd'));">
                            <option value='' selected="selected">-省份-</option>
                          </select>
                          <select name="cdd" id="cdd" style="width: 65px" onchange="changecity(document.getElementById('mdd').value,document.getElementById('cdd').value,document.getElementById('xian'))">
                            <option value="" selected="selected">-城市-</option>
                          </select>
                          <select name="xian" id="xian" style="width: 65px">
                            <option value="" selected="selected">-县-</option>
                          </select>
                          <script language="JavaScript" type="text/javascript">
                            setup(document.getElementById("mdd"));
                          </script>                       </td>
                        <td>
                            <div onclick="SetMap(); return false;" style="cursor: pointer; width:81px;">
                        <img src="images/search.gif" alt="中国公路里程查询" width="81" height="26" style="vertical-align: middle;" /></div></td>                        
                        <td><table width="380" border="0" cellspacing="0" cellpadding="0">
                         <tr>
                          <td width="50"> </td>
                          <td width="19"><span style="padding-top: 2px;"></span></td>
                          <td width="90" style="font-size: 12px;"> 出发城市 </td>
                          <td>
                            <input name="farea" type="text" id="farea" size="10" /></td>
                          <td width="26" align="center" style="font-size: 12px;"> 到 </td>
                          <td width="110"><input name="tarea" type="text" id="tarea" size="10" />
                          </td>
                          <td><div onclick="SetMap2(); return false;" style="cursor: pointer; width:81px;"> <img src="images/search.gif" alt="中国公路里程查询" width="81" height="26" style="vertical-align: middle;" /></div></td>
                         </tr>
                        </table></td>
                      </tr>
      </table>   
      </div>  </td>
   </tr>
   <tr>
    <td><div style="border: #cccccc 1px solid; padding:5px;"></div></td>
   </tr>   
   <tr>
    <td> </td>
   </tr>
   <tr>
    <td valign="top">
    <div style="float: left; width: 670px; vertical-align: top;">
      <div style="height: 500px; border: 1px solid gray" id="container">      </div>
    </div>
    <div style="float: right; width: 300px; vertical-align: top;">
      <div style="border: #cccccc 1px solid;">
        <div class="content_title" style="color:Red; background-image:url();border-bottom:solid 1px #ccc; height:30px; text-align:center; font-weight:bold; line-height:30px;" id="div_title">查询结果</div>
        <div id="div_gongli" style="color:#336600; font-weight:bold; padding-left:5px; line-height:35px; font-size:14px;"></div>
        <div id="results" style="font-size: 12px;">        </div>
      </div>
    </div>    </td>
   </tr>
  </table></td>
 </tr>
</table>
  </div>
</body>
</html>
<script language="javascript" type="text/javascript">
  var map = new BMap.Map("container");
  //var mapStyle = { style: "mapbox" }
  //map.setMapStyle(mapStyle);
  map.centerAndZoom(new BMap.Point(116.404, 39.915), 14);
  //map.centerAndZoom(point, 11);
  map.addControl(new BMap.NavigationControl()); // 添加平移缩放控件
  map.addControl(new BMap.OverviewMapControl()); //添加缩略地图控件
  map.enableScrollWheelZoom(); //启用滚轮放大缩小
  map.setMapStyle({ style: "mapbox" });
  function SetMap() {
    var oGl = document.getElementById("div_gongli");
    var ofprovince = document.getElementById("AreaDept1_Province")
    var ofname = document.getElementById("AreaDept1_Prefecture")
    var ofxian = document.getElementById("AreaDept1_Xian")
    var otprovince = document.getElementById("mdd")
    var otname = document.getElementById("cdd");
    var otxian = document.getElementById("xian")
    var output = "全程:";
    if (ofname.value == "") {
      alert('请输入出发地!');
      return;
    }
    if (otname.value == "") {
      alert('请输入到达地!');
      return;
    }
    var title = document.getElementById("div_title");
    title.innerText = "'" + ofprovince.value + ofname.value + ofxian.value + "到" + otprovince.value + otname.value + otxian.value + "' 查询结果";
    var searchComplete = function(results) {
      if (transit.getStatus() != BMAP_STATUS_SUCCESS) { return; }
      var plan = results.getPlan(0);
      output += plan.getDistance(true);       //获取距离
      output += "/";
      output += plan.getDuration(true);        //获取时间
    }
    var transit = new BMap.DrivingRoute(map, { renderOptions: { map: map, panel: "results", autoViewport: true },
      onSearchComplete: searchComplete,
      onPolylinesSet: function() { oGl.innerText = output; }
    });
    transit.search(ofprovince.value + ofname.value + ofxian.value, otprovince.value + otname.value + otxian.value);
  }
  function SetMap2() {
    var oGl = document.getElementById("div_gongli");
    var ofname = document.getElementById("farea");
    var otname = document.getElementById("tarea");
    var output = "全程:";
    if (ofname.value == "") {
      alert('请输入出发地!');
      return;
    }
    if (otname.value == "") {
      alert('请输入到达地!');
      return;
    }
    var title = document.getElementById("div_title");
    title.innerText = "'" + ofname.value + "到" + otname.value + "' 查询结果";
    var searchComplete = function(results) {
      if (transit.getStatus() != BMAP_STATUS_SUCCESS) { return; }
      var plan = results.getPlan(0);
      output += plan.getDistance(true);       //获取距离
      output += "/";
      output += plan.getDuration(true);        //获取时间
    }
    var transit = new BMap.DrivingRoute(map, { renderOptions: { map: map, panel: "results", autoViewport: true },
      onSearchComplete: searchComplete,
      onPolylinesSet: function() { oGl.innerText = output; }
    });
    transit.search(ofname.value, otname.value);
  }
</script>
Copy after login

Let me introduce how C# calculates the driving distance between two places based on Baidu map

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;}
#l-map{height:100%;width:78%;float:left;border-right:2px solid #bcbcbc;}
#r-result{height:100%;width:20%;float:left;}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api&#63;v=1.4"></script>
<title>计算驾车时间与距离</title>
</head>
<body>
<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("allmap");
map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
var output = "从上地到西单驾车需要";
var searchComplete = function (results){
  if (transit.getStatus() != BMAP_STATUS_SUCCESS){
    return ;
  }
    var plan = results.getPlan(0);
    output += plan.getDuration(true) + "\n";        //获取时间
    output += "总路程为:" ;
    output += plan.getDistance(true) + "\n";       //获取距离
}
var transit = new BMap.DrivingRoute(map, {renderOptions: {map: map},
  onSearchComplete: searchComplete,
  onPolylinesSet: function(){    
    setTimeout(function(){alert(output)},"1000");
  }});
transit.search("上地", "西单");
</script>
Copy after login
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 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.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 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 and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles