從高德地圖抓取數據


老板是搞交通的,要我從高德上抓數據放到自己的數據庫中。說做就做!


一、工具


1、VisualStudio2010

或其他Html編輯器
2、Access數據庫

使用mysql或其他數據庫需要服務器支持,這里為了方便就使用access
3、IE瀏覽器


二、步驟


獲取高德地圖點的屬性

使用JavaScript代碼alert 出poiArr[i]對象的所有屬性,為創建表格做准備


建立Access數據庫表

依據上面所得出的數據,創建poi表,字段有id(主鍵)、name、type、latitude、lotitude、longitude、address和tel。

為了方便,全部使用文本類型


編寫Html代碼


<span style="font-size:18px;"><!DOCTYPE HTML>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>輸入提示后查詢</title>
	<style type="text/css">
		body{
			margin:0;
			height:100%;
			width:100%;
			position:absolute;
			font-size:12px;
		}
		#mapContainer{
			position: absolute;
			top:0;
			left: 0;
			right:0;
			bottom:0;
		}
		
		#tip{
			background-color:#fff;
			border:1px solid #ccc;
			padding-left:10px;
			padding-right:2px;
			position:absolute;
			min-height:65px;
			top:10px;
			font-size:12px;
			right:10px;
			border-radius:3px;
			overflow:hidden;
			line-height:20px;
			min-width:400px;
		}
		#tip input[type="button"]{
			background-color: #0D9BF2;
			height:25px;
			text-align:center;
			line-height:25px;
			color:#fff;
			font-size:12px;
			border-radius:3px;
			outline: none;
			border:0;
			cursor:pointer;
		}
		
		#tip input[type="text"]{
			height:25px;
			border:1px solid #ccc;
			padding-left:5px;
			border-radius:3px;
			outline:none;
		}
		
		#result1{
			max-height:300px;
		}
	</style>
</head>
<body>
    <div id="mapContainer" ></div>
    <div id="tip">
        <b>請輸入關鍵字:</b>
        <input type="text" id="keyword" name="keyword" value="" onkeydown='keydown(event)' style="width: 95%;"/>
        <div id="result1" name="result1"></div>
    </div>
    
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=你的密鑰"></script>
	<script type="text/javascript">
		var windowsArr = [];
		var marker = [];
		var mapObj = new AMap.Map("mapContainer", {
			resizeEnable: true,
	        view: new AMap.View2D({
	        	resizeEnable: true,
	            center:new AMap.LngLat(113.385773,23.061727),//地圖中心點
	            zoom:13//地圖顯示的縮放級別
	        }),
	        keyboardEnable:false
	    });
			
	    document.getElementById("keyword").onkeyup = keydown;
		//輸入提示
		function autoSearch() {
		    var keywords = document.getElementById("keyword").value;
		    var auto;
		    //加載輸入提示插件
		        AMap.service(["AMap.Autocomplete"], function() {
		        var autoOptions = {
		            city: "" //城市,默認全國
		        };
		        auto = new AMap.Autocomplete(autoOptions);
		        //查詢成功時返回查詢結果
		        if ( keywords.length > 0) {
		            auto.search(keywords, function(status, result){
		            	autocomplete_CallBack(result);
		            });
		        }
		        else {
		            document.getElementById("result1").style.display = "none";
		        }
		    });
		}
		 
		//輸出輸入提示結果的回調函數
		function autocomplete_CallBack(data) {
		    var resultStr = "";
		    var tipArr = data.tips;
		    if (tipArr&&tipArr.length>0) {                 
		        for (var i = 0; i < tipArr.length; i++) {
		            resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1)
		                        + ",this)' onclick='selectResult(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1)
		                        + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>";
		        }
		    }
		    else  {
		        resultStr = " π__π 親,人家找不到結果!<br />要不試試:<br />1.請確保所有字詞拼寫正確<br />2.嘗試不同的關鍵字<br />3.嘗試更寬泛的關鍵字";
		    }
		    document.getElementById("result1").curSelect = -1;
		    document.getElementById("result1").tipArr = tipArr;
		    document.getElementById("result1").innerHTML = resultStr;
		    document.getElementById("result1").style.display = "block";
		}
		 
		//輸入提示框鼠標滑過時的樣式
		function openMarkerTipById(pointid, thiss) {  //根據id打開搜索結果點tip 
		    thiss.style.background = '#CAE1FF';
		}
		 
		//輸入提示框鼠標移出時的樣式
		function onmouseout_MarkerStyle(pointid, thiss) {  //鼠標移開后點樣式恢復 
		    thiss.style.background = "";
		}
		 
		//從輸入提示框中選擇關鍵字並查詢
		function selectResult(index) {
		    if(index<0){
		        return;
		    }
		    if (navigator.userAgent.indexOf("MSIE") > 0) {
		        document.getElementById("keyword").onpropertychange = null;
		        document.getElementById("keyword").onfocus = focus_callback;
		    }
		    //截取輸入提示的關鍵字部分
		    var text = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");
			var cityCode = document.getElementById("divid" + (index + 1)).getAttribute('data');
		    document.getElementById("keyword").value = text;
		    document.getElementById("result1").style.display = "none";
		    //根據選擇的輸入提示關鍵字查詢
		    mapObj.plugin(["AMap.PlaceSearch"], function() {       
		        var msearch = new AMap.PlaceSearch();  //構造地點查詢類
		        AMap.event.addListener(msearch, "complete", placeSearch_CallBack); //查詢成功時的回調函數
				msearch.setCity(cityCode);
		        msearch.search(text);  //關鍵字查詢查詢
		    });
		}
		 
		//定位選擇輸入提示關鍵字
		function focus_callback() {
		    if (navigator.userAgent.indexOf("MSIE") > 0) {
		        document.getElementById("keyword").onpropertychange = autoSearch;
		   }
		}
		 
		//輸出關鍵字查詢結果的回調函數
		function placeSearch_CallBack(data) {
		    //清空地圖上的InfoWindow和Marker
		    windowsArr = [];
		    marker     = [];
		    mapObj.clearMap();
		    var resultStr1 = "";
		    var poiArr = data.poiList.pois;
		    var resultCount = poiArr.length;
		   	//allPrpos ( poiArr[1] );name,id,lng,lat,type,address,tel

		    for (var i = 0; i < resultCount; i++) {
		        resultStr1 += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名稱: " + poiArr[i].name + "</font></h3>";
		            resultStr1 += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
		            var longitude = poiArr[i].location.lng;
             		var latitude = poiArr[i].location.lat;
             		addStation(poiArr[i].id,poiArr[i].name,longitude,latitude,poiArr[i].type,poiArr[i].address,poiArr[i].tel);
		            addmarker(i, poiArr[i]);
		    }
		    mapObj.setFitView();
		}
		 
		//鼠標滑過查詢結果改變背景樣式,根據id打開信息窗體
		function openMarkerTipById1(pointid, thiss) {
		    thiss.style.background = '#CAE1FF';
		    windowsArr[pointid].open(mapObj, marker[pointid]);
		}
		 
		//添加查詢結果的marker&infowindow   
		function addmarker(i, d) {
		    var lngX = d.location.getLng();
		    var latY = d.location.getLat();
		    var markerOption = {
		        map:mapObj,
		        icon:"http://webapi.amap.com/images/" + (i + 1) + ".png",
		        position:new AMap.LngLat(lngX, latY)
		    };
		    var mar = new AMap.Marker(markerOption);         
		    marker.push(new AMap.LngLat(lngX, latY));
		 
		    var infoWindow = new AMap.InfoWindow({
		        content:"<h3><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></h3>" + TipContents(d.type, d.address, d.tel),
		        size:new AMap.Size(300, 0),
		        autoMove:true, 
		        offset:new AMap.Pixel(0,-30)
		    });
		    windowsArr.push(infoWindow);
		    var aa = function (e) {infoWindow.open(mapObj, mar.getPosition());};
		    AMap.event.addListener(mar, "mouseover", aa);
		}
		 
		//infowindow顯示內容
		function TipContents(type, address, tel) {  //窗體內容
		    if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
		        type = "暫無";
		    }
		    if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
		        address = "暫無";
		    }
		    if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
		        tel = "暫無";
		    }
		    var str = "  地址:" + address + "<br />  電話:" + tel + " <br />  類型:" + type;
		    return str;
		}
		function keydown(event){
		    var key = (event||window.event).keyCode;
		    var result = document.getElementById("result1")
		    var cur = result.curSelect;
		    if(key===40){//down
		        if(cur + 1 < result.childNodes.length){
		            if(result.childNodes[cur]){
		                result.childNodes[cur].style.background='';
		            }
		            result.curSelect=cur+1;
		            result.childNodes[cur+1].style.background='#CAE1FF';
		            document.getElementById("keyword").value = result.tipArr[cur+1].name;
		        }
		    }else if(key===38){//up
		        if(cur-1>=0){
		            if(result.childNodes[cur]){
		                result.childNodes[cur].style.background='';
		            }
		            result.curSelect=cur-1;
		            result.childNodes[cur-1].style.background='#CAE1FF';
		            document.getElementById("keyword").value = result.tipArr[cur-1].name;
		        }
		    }else if(key === 13){
		        var res = document.getElementById("result1");
				if(res && res['curSelect'] !== -1){
					selectResult(document.getElementById("result1").curSelect);
				}
		    }else{
		        autoSearch();
		    }
		}
		/* 
		* 用來遍歷指定對象所有的屬性名稱和值 
		* obj 需要遍歷的對象 
		* author: Jet Mah 
		*/ 
		function allPrpos ( obj ) { 
			// 用來保存所有的屬性名稱和值 
			var props = "" ; 
			// 開始遍歷 
			for ( var p in obj ){ 
			// 方法 
			if ( typeof ( obj [ p ]) == " function " ){ 
			obj [ p ]() ; 
			} else { 
			// p 為屬性名稱,obj[p]為對應屬性的值 
			props += p + " = " + obj [ p ] + " \t " ; 
			} 
			} 
			// 最后顯示所有的屬性 
			alert ( props ) ; 
		} 


		//Insert data into the database
        function addStation(id,name,lng,lat,type,address,tel){
        	var filePath = location.href.substring(0, location.href.indexOf("GaodeToaccess.htm"));  
            var path = filePath + "hzyGaoDe.mdb";  
            //去掉字符串中最前面的"files://"這8個字符。  
            pathpath = path.substring(8);  
           //alert(pathpath);
			var conn=new ActiveXObject("ADODB.Connection");
			conn.Open("DBQ="+pathpath+";DRIVER={Microsoft Access Driver (*.mdb)};");
			var sql = "insert into poi(id,name,lng,lat,type,address,tel) values('"+id+"','"+name+"','"+lng+"','"+lat+"','"+type+"','"+address+"','"+tel+"')";
			//alert(sql);
			try{
				conn.execute(sql);
			}
			catch(e){
				document.write(e.description);
			}
		}	
	</script>
</body>
</html>						
</span>


三、實驗效果

打開網頁,在關鍵詞搜索框中輸入要搜索的地點

在下拉列表框中選擇對應的地點

發現地圖出現與搜索地點相關的幾個點

然后打開access數據庫表

發現記錄數增加


四、實驗注意要點


連接數據庫時mdb文件必須給出絕對路徑

這里采用的方法是把mdb文件和html文件放在同一目錄下,利用html文件獲取目錄的路徑

代碼片段如下

var filePath = location.href.substring(0,location.href.indexOf("GaodeToaccess.htm")); 

           var path = filePath + "hzyGaoDe.mdb"; 

           //去掉字符串中最前面的"files://"這8個字符。 

           pathpath = path.substring(8);

                     varconn=new ActiveXObject("ADODB.Connection");

                     conn.Open("DBQ="+pathpath+";DRIVER={MicrosoftAccess Driver (*.mdb)};");

 


主鍵不要重復

插入數據時傳的id最好使用高德地圖點對象的Id,這樣可以保證主鍵不會重復,數據可以順利插入

代碼片段如下

addStation(poiArr[i].id,poiArr[i].name,longitude,latitude,poiArr[i].type,poiArr[i].address,poiArr[i].tel);

 

Key密鑰

<script type="text/javascript"src="http://webapi.amap.com/maps?v=1.3&key=xxx"></script>

要填入你自己申請的密鑰




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM