[WebGIS] Demo3-使用高德地图Web服务|路线规划

文章目录

  • 高德地图路径规划服务
  • 使用
  • 例子
    • 目录介绍
    • 主要代码
      • HTML页面
      • 高德地图服务amap-direction.js
      • 坐标转换coordinateUtils.js
      • 点、线、面符号统一管理symbol.js
      • 加载天地图底图
    • 结果

高德地图路径规划服务

http://lbs.amap.com/api/webservice/guide/api/direction
提供两个点之间的路线:步行、公交、驾车

使用

  1. 申请高德地图Web服务的Key
  2. 按申请的参数拼接URL
  3. 使用JS的AJAX异步请求HTTP服务
  4. 获取参数使用

这里写图片描述

例子

[WebGIS] Demo3-使用高德地图Web服务|路线规划_第1张图片

JS框架:jQuery(操作DOM,异步发送请求)
ArcGIS API for javascript:展示路径规划的结果
底图:天地图(坐标系4326)
项目为Hbuild工程文件
此例子为小生项目例子,还未进行封装与改善
下载地址 若没有积分请在评论处留邮箱(上传完积分就不准改了!看到第一时间发)

目录介绍

[WebGIS] Demo3-使用高德地图Web服务|路线规划_第2张图片

主要代码

HTML页面


<html>
	<head>
		<meta charset="UTF-8">
		<title>高德地图路线规划title>
		
		<link rel="stylesheet" type="text/css" href="https://js.arcgis.com/3.21/esri/css/esri.css" />
	    <link rel="stylesheet" type="text/css" href="https://js.arcgis.com/3.21/dijit/themes/tundra/tundra.css"/>
	    <script type="text/javascript">
	        var dojoConfig = {
	            parseOnLoad: true,
	            packages: [{ //解释:require(["js/.."],function(){}) 中  js/ 即为 location的值
		            name: "js", //对应require引用包里的js 
		            location: location.pathname.replace(/\/[^/]*$/, '') + '/js' //对应的路径
		        }]
	        };
	    script>
	    <script type="text/javascript" src="https://js.arcgis.com/3.21/init.js">script>
	    
	    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js">script>
	    <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js">script>
	    <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
	    
	head>
	<body>
		<div id="map" style="width:900px; height:580px; border:1px solid #000;">div>
<script>
var map;
var selectedSpotsBuffer_spotsMap = { //模拟项目数据
	"1" : {
		geometry : {
			x : 118.13214548600001,
			y : 24.424820321000027
		},
		attributes :  {
			id : 1,
			name :"白石炮台遗址",
			recommendtime:120,
			total:76.16926103,
			x:118.13214548600001,
			y:24.424820321000027
		}
	},
	"6" : {
		geometry : {
			x : 118.11964657700003,
			y : 24.434867303000033
		},
		attributes :  {
			id : 6,
			name :"启明寺",
			recommendtime:90,
			total:88.32278481,
			x:118.11964657700003,
			y:24.434867303000033
		}
	}
};
$(document).ready(function(){
	$.getScript("js/tools/symbol.js",function () { //引入符号系统
        initSymbol();
    });
	require(["esri/map", "js/tools/TDTLayer","js/tools/TDTAnnoLayer","esri/layers/GraphicsLayer"], 
	function (Map, TDTLayer,TDTAnnoLayer,GraphicsLayer) {
        map = new Map("map", { //初始化底图
            center: [118.15, 24.55],
            zoom: 11,
            logo : false //logo
        });
        var baselayer = new TDTLayer(); //加载天地图图层
        map.addLayer(baselayer);
        var annolayer = new TDTAnnoLayer();//加载天地图图层
        map.addLayer(annolayer);
       	
       	var direction = new GraphicsLayer({ //新建路线规划的图层 用来显示路线规划结果
			id : "direction"
		});
		map.addLayer(direction);
		
        $.getScript("js/tools/coordinateUtils.js",function(){ //加载坐标转换工具
	   		$.getScript("js/tools/amap-direction.js",function(){ //加载高德地图路径规划
	   			//两种调用方法
//	   			walking("direction","白石炮台遗址->启明寺",selectedSpotsBuffer_spotsMap["1"]["geometry"],selectedSpotsBuffer_spotsMap["6"]["geometry"]);
	   			transit("direction","白石炮台遗址->启明寺",{"origin" : selectedSpotsBuffer_spotsMap["1"]["geometry"],
	   				"destination" : selectedSpotsBuffer_spotsMap["6"]["geometry"],
	   				"city" : "厦门"
	   			});
	   		});
	    });
	});
});
script>
	body>
html>

高德地图服务amap-direction.js

/**
 * @function 高德地图路径导航服务
 * @description 依赖于coordinateUtils.js包
 */

var AMAP_SERVICE_KEY = "4fac3db************7db1c7"; //key 请自己申请
/**
 * @function 步行
 * @parma layerName 加载的图层名
 * @parma _routeName 路线名称
 * @param originGeometry,destinationGeometry起始点geometry
 */
var steps;
var routeName;
var layerName;
function walking(_layerName,_routeName,originGeometry,destinationGeometry) {
	layerName = _layerName;
	routeName = _routeName;
	var origin = wgs84togcj02(originGeometry.x,originGeometry.y); //坐标系转换
	var destination = wgs84togcj02(destinationGeometry.x,destinationGeometry.y);
	var serviceUrl =
	"http://restapi.amap.com/v3/direction/walking?output=JSON&origin="+origin+"&destination="+destination+"&key="+AMAP_SERVICE_KEY;
	$.ajax({ //高德地图HTTP服务
		type:"get",
		url:serviceUrl,
		async:true,
		success : function(result){ //成功返回结果
			result = eval(result); //解析JSON格式的字符串
			steps = result.route.paths[0].steps; //取出步行数组
			handleResult_walking(steps); //处理步行数组
		}
	});
}
/**
 * @function 处理steps 步行数组
 * @param {Object} result
 */
function handleResult_walking(steps) {
	//因服务中所给路线的经纬度为字符串,所以我们将其转换成数组,并覆盖
	$.each(steps, function(index,value) {
		//把字符串变成 坐标数组,然后转换
		var latAndLons = value.polyline.split(";");
		var points = [];
		$.each(latAndLons,function(index,value){
			var point = value.split(","); //一个点的经纬度 [x,y]
			$.each(point, function(index,value) {//[x,y]字符串转为float
				point[index] -= 0;
			});
			point = gcj02towgs84(point[0],point[1]);//转换坐标
			points.push(point);//放入集合
			console.log(points);
		});
		value.polyline = points; //覆盖原来的字符串
		console.log(value.polyline);
	});
	drawRoute_walking(routeName,steps); //画出解决方案
}
function drawRoute_walking(routeName,steps){
	$.each(steps,function(index,value){
		var lineName = routeName + " 第"+(index+1)+"步"; //步数名称
		console.log(lineName);console.log(value);
		drawLine_walking(lineName,value); //画线
	});
}
function drawLine_walking(lineName,lineMap) {
	require([
  		"esri/geometry/Polyline",
  		"esri/graphic",
  		"esri/InfoTemplate",
  		"esri/layers/GraphicsLayer"
	], function(Polyline,Graphic,InfoTemplate,GraphicsLayer) {
  		var polylineJson = { //线对象参数JSON格式
		    "paths":[
		    	lineMap.polyline
		    ],
		    "spatialReference":{
		    	"wkid":4326
		    }
	  	};
  		var polyline = new Polyline(polylineJson); //创建线对象
	  	console.log(polyline);
	 	var attr = { //该地理实体的属性
	 		name : lineName,
	 		action : lineMap.action,
	 		distance : lineMap.distance,
	 		instruction : lineMap.instruction,
	 		road :lineMap.road
	 	};
	 	//地理实体的信息窗口
	 	var infoTemplate = new InfoTemplate("${name}", "方向:${action}
介绍:${instruction}
距离:${distance}米
路名:${road}"
); //创建客户端图形 var graphic = new Graphic(polyline,symbolMap["line_default"],attr,infoTemplate); //加载到地图上 map.getLayer(layerName).add(graphic); }); } /** * @function 公交 * @parma layerName 加载的图层名 * @param routeName 线路名称 * @param paramsMap参数信息 origin lon,lat(经度,纬度),如117.500244, 40.417801 经纬度小数点不超过6位 必须 destination on,lat(经度,纬度),如117.500244, 40.417801 经纬度小数点不超过6位 必须 city 城市名 支持市内公交换乘/跨城公交的起点城市,规则:城市名称/citycode 必须 strategy 0:最快捷模式;1:最经济模式;2:最少换乘模式;3:最少步行模式;5:不乘地铁模式 nightflag 是否计算夜班车,1:是;0:否 date 根据出发日期筛选,格式:date=2014-3-19 time 根据出发时间筛选,格式:time=22:34 */ var transitRoute; //{} 有origin、destination、distance、taxi_cost、transits乘车方案 function transit(_layerName,_routeName,paramsMap) { layerName = _layerName; routeName = _routeName; paramsMap.origin = wgs84togcj02(paramsMap.origin.x,paramsMap.origin.y); paramsMap.destination = wgs84togcj02(paramsMap.destination.x,paramsMap.destination.y); var serviceUrl = "http://restapi.amap.com/v3/direction/transit/integrated?"; $.each(paramsMap, function(key,value) { serviceUrl += key +"="+value+"&"; }); serviceUrl += "output=JSON&key="+AMAP_SERVICE_KEY; console.log(serviceUrl); $.ajax({ type:"get", url:serviceUrl, async:true, success : function(result){ result = eval(result); console.log(result); transitRoute = result.route; $.each(transitRoute.transits, function(index,value) { //transits [] 遍历乘车方案 //value {} 一种乘车方案 有cost duration nightflag walking_distance distance missed segments var segments = value.segments; //[] 乘车方案分几步 $.each(segments, function(index,value) { handleResult_walking(value.walking.steps); handleResult_bus(value.bus.buslines); }); }); } }); } function handleResult_bus(buslines) { //处理数据 $.each(buslines, function(index,value) { //把字符串变成 坐标数组,然后转换 console.log(value.polyline); var latAndLons = value.polyline.split(";"); var points = []; $.each(latAndLons,function(index,value){ var point = value.split(","); //一个点的经纬度 [x,y] $.each(point, function(index,value) {//[x,y]字符串转为float point[index] -= 0; }); point = gcj02towgs84(point[0],point[1]);//转换坐标 points.push(point);//放入集合 console.log(points); }); value.polyline = points; console.log(value.polyline); }); drawRoute_bus(buslines); //画公交线 } function drawRoute_bus(buslines) { $.each(buslines,function(index,value){ var lineName = routeName + " 第"+(index+1)+"步 "+ value.name; console.log(lineName);console.log(value); drawLine_bus(lineName,value); }); } function drawLine_bus(lineName,lineMap) { require([ "esri/geometry/Polyline", "esri/graphic", "esri/InfoTemplate" ], function(Polyline,Graphic,InfoTemplate) { var polylineJson = { "paths":[ lineMap.polyline ], "spatialReference":{ "wkid":4326 } }; var polyline = new Polyline(polylineJson); console.log(polyline); var attr = { name : lineName, distance : lineMap.distance, type : lineMap.type, departure_stop : lineMap.departure_stop.name, arrival_stop : lineMap.arrival_stop.name }; var infoTemplate = new InfoTemplate("${name}", "类型:${type}
起始站:${departure_stop}
下车站:${arrival_stop}
距离:${distance}米"
); var graphic = new Graphic(polyline,symbolMap["line_default"],attr,infoTemplate); map.getLayer(layerName).add(graphic); }); }

坐标转换coordinateUtils.js

http://blog.csdn.net/summer_dew/article/details/77688210

点、线、面符号统一管理symbol.js

统一管理利于后期修改样式,不用在每个JS文件中找样式
也可以对样式方案进行扩展,用户可自行设置属于自己的一套样式

/**
 * Created by passerQi on 2017/8/23.
 * 说明:符号样式统一管理
 */
var symbolMap = {}; //存储符号系统的map
function initSymbol(){
    require([
        "esri/symbols/PictureMarkerSymbol",
        "esri/symbols/SimpleLineSymbol", //线符号
        "esri/symbols/SimpleMarkerSymbol", //点符号
        "esri/symbols/SimpleFillSymbol", //面符号
	    ], function(PictureMarkerSymbol,SimpleLineSymbol,SimpleMarkerSymbol,SimpleFillSymbol) {
	        //默认符号样式
	        symbolMap["line_default"] = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new dojo.Color([236, 176, 25]), 3);
	        symbolMap["point_default"] = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE,10, symbolMap["default_line"], new dojo.Color([236, 176, 25]));
	        symbolMap["fill_default"] = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, symbolMap["default_line"],  new dojo.Color([236, 176, 25]));
        //点
        symbolMap["point_main_blue"] = new PictureMarkerSymbol('img/point_main_blue.png', 25, 25);
        symbolMap["point_green"] = new PictureMarkerSymbol('img/point_green.png', 25, 25);
        symbolMap["point_restaurant"] = new PictureMarkerSymbol('img/point_main_blue.png', 25, 25);
        
        //面
        for (var i=0; i<9; i++) {
        	if (i%3===0) {
        		symbolMap["fill_"+i] = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, symbolMap["default_line"],  new dojo.Color([236, 176, 50*i,0.2]));
        	} else if ( i%3===1) {
        		symbolMap["fill_"+i] = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, symbolMap["default_line"],  new dojo.Color([236, 50*i, 25,0.2]));
        	} else {
        		symbolMap["fill_"+i] = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, symbolMap["default_line"],  new dojo.Color([50*i, 176, 25,0.2]));
        	}
        }
        
    });
}

加载天地图底图

http://blog.csdn.net/summer_dew/article/details/77687688

结果

[WebGIS] Demo3-使用高德地图Web服务|路线规划_第3张图片

你可能感兴趣的:(WebGIS)