1. 程式人生 > >[WebGIS] Demo3-使用高德地圖Web服務|路線規劃

[WebGIS] Demo3-使用高德地圖Web服務|路線規劃

高德地圖路徑規劃服務

使用

  1. 申請高德地圖Web服務的Key
  2. 按申請的引數拼接URL
  3. 使用JS的AJAX非同步請求HTTP服務
  4. 獲取引數使用

這裡寫圖片描述

例子

這裡寫圖片描述

JS框架:jQuery(操作DOM,非同步傳送請求)
ArcGIS API for javascript:展示路徑規劃的結果
底圖:天地圖(座標系4326)
專案為Hbuild工程檔案
此例子為小生專案例子,還未進行封裝與改善
下載地址 若沒有積分請在評論處留郵箱(上傳完積分就不準改了!看到第一時間發)

目錄介紹

這裡寫圖片描述

主要程式碼

HTML頁面

<!DOCTYPE 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}<br/>介紹:${instruction}<br/>距離:${distance}米<br/>路名:${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}<br/>起始站:${departure_stop}<br/>下車站:${arrival_stop}<br/>距離:${distance}米"); 
  		var graphic = new Graphic(polyline,symbolMap["line_default"],attr,infoTemplate);
  		map.getLayer(layerName).add(graphic);
	});
}

座標轉換coordinateUtils.js

點、線、面符號統一管理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]));
        	}
        }
        
    });
}

載入天地圖底圖

結果

這裡寫圖片描述