goole map|路线查询|地点查询|公交查询|周边查询
前一段时间做了一个google地图的应用,在做的过程中由于参考资料比较少,英语水平也比较有限。在做的过程中遇到一不少麻烦。
目前基本功能都已经实现,希望能给同样遇到问题的同学一个参考。也欢迎对各式问题与我交流。
由于时间仓促不算很完善,希望各位大侠分享自已更好的的作品,共同进步。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>MapTools</title> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script> <script type="text/javascript"> var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']; var deflocation; //= new google.maps.LatLng(24.498708, 118.110924); var geocoder; var map; var initialLocation; var browserSupportFlag = new Boolean(); var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var stepDisplay; var infoWindow = new google.maps.InfoWindow(); var zindex = 1; function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } function SetDefaultCenter() { var ll = getQueryString("ll"); var z = getQueryString("z"); if (ll != null) { l1 = ll.split(','); var l = new google.maps.LatLng(l1[0], l1[1]); map.setCenter(l); map.setZoom(parseInt(z)); var marker = new google.maps.Marker({ map: map, position: l }); markersArray.push(marker); } else { defCity ='厦门'; geocoder.geocode({ 'address': defCity }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { deflocation = results[0].geometry.location; map.setCenter(deflocation); } }); } } function initialize() { geocoder = new google.maps.Geocoder(); var myOptions = { zoom: 11, center: deflocation, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("rDiv"), myOptions); SetDefaultCenter(); var rendererOptions = { map: map } directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions) directionsDisplay.setMap(map); // Instantiate an info window to hold step text. stepDisplay = new google.maps.InfoWindow(); } //^^^^^^初始化^^^^^^^^ //+++++地址查询+++++ //marker数组 var markersArray = []; function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } markersArray.length = 0; } directionsDisplay.setMap(null); $("#lDiv").html(""); $("#warnings_panel").html(""); } function PlaceSearch(addr) { var request = { location: map.center, query: addr, radius: 50000 }; service = new google.maps.places.PlacesService(map); service.textSearch(request, placeSearchCallBack); } function placeSearchCallBack(results, status) { $('#lDiv').html(""); if (status == google.maps.places.PlacesServiceStatus.OK) { //map.setCenter(results[0].geometry.location); deflocation = results[0].geometry.location; var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < results.length && i < 8; i++) { var place = results[i]; var marker = new google.maps.Marker({ map: map, icon: '/images/micon' + (i + 1) + '.png', position: place.geometry.location, zIndex: ++zindex }); attachInstructionText(marker, place.name + '<br/> <small>' + place.formatted_address + '</small>'); $("#lDiv").append('<a id="a' + i + '" href="javascript:void(0)" >' + arr[i] + ',' + place.name + '</a>' + '<input id="h' + i + '" type="hidden" value="' + place.geometry.location + '">' + '<br/>'); $("#a" + i).click(function () { stepDisplay.setContent(place.name + '<br/> <small>' + place.formatted_address + '</small>'); var mk= markersArray[parseInt($(this).attr("id").replace('a', ''))]; stepDisplay.open(map,mk); mk.setZIndex(++zindex); }) bounds.extend(place.geometry.location); markersArray.push(marker); marker.setTitle(place.name + '_' + place.formatted_address); } if (results.length > 1) { map.fitBounds(bounds); } else { map.setCenter(results[0].geometry.location); map.setZoom(11); } } else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) { $("#lDiv").html($("#noneContent").html()) } else { //alert("查询时发生了错误: " + status); } } function attachInstructionText(marker, text) { google.maps.event.addListener(marker, 'click', function () { stepDisplay.setContent(text); stepDisplay.open(map, marker); marker.setZIndex(++zindex); }); } //^^^^^^地址查询^^^^^^ //++++++路线查询++++++ var travelMode = google.maps.TravelMode.TRANSIT; var start; var end; function calcRoute() { var rendererOptions = { map: map } directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions) directionsDisplay.setMap(map); if ($("#tm").val() == "bus") { travelMode = google.maps.TravelMode.TRANSIT; } else { travelMode = google.maps.TravelMode.DRIVING; } start = document.getElementById("startAddress").value; end = document.getElementById("endAddress").value; var request = { origin: start, destination: end, provideRouteAlternatives: true, travelMode: travelMode }; directionsService.route(request, function (response, status) { $('#lDiv').html(""); if (status == google.maps.DirectionsStatus.OK) { var warnings = document.getElementById("warnings_panel"); warnings.innerHTML = "" + response.routes[0].warnings + ""; directionsDisplay.setDirections(response); if (travelMode == google.maps.TravelMode.TRANSIT) { showTRANSITDetail(response); } else { showDRIVINGDetail(response); } } else if (status == google.maps.DirectionsStatus.ZERO_RESULTS || status == google.maps.DirectionsStatus.NOT_FOUND) { $("#lDiv").html($("#noneContent").html()) } else { //alert("查询时发生了错误: " + status); } }); } function showTRANSITDetail(directionResult) { var str1, str2, str3 = ""; for (var j = 0; j < directionResult.routes.length && j < 3; j++) { var myRoute = directionResult.routes[j]; $("#lDiv").append('<h4><span id="span' + j + '"></span></h4><br/>'); str1 = '路线' + (j + 1); str2 = '<b>从' + start + '出发。</b><br/>' $("#lDiv").append(str2); var cl = myRoute.legs[0]; for (var i = 0; i < cl.steps.length; i++) { var s = cl.steps[i]; if (s.travel_mode == google.maps.TravelMode.TRANSIT) { if (str3.length > 0) str1 += ' 转'; str1 += ' ' + s.transit.line.short_name; str3 = ' 乘坐' + s.transit.line.short_name + s.instructions + '<br/>'; str3 += ' 在' + s.transit.departure_stop.name + '站上车,到' + s.transit.arrival_stop.name + '站下车<br/>'; str3 += ' ' + s.distance.text + '-' + s.duration.text + '<br/>'; $("#lDiv").append(str3); } else { str3 = ' ' + s.instructions + '<br/>'; str3 += ' ' + s.distance.text + '-' + s.duration.text + '<br/>'; $("#lDiv").append(str3); str3 = ""; } $("#lDiv").append(str3); } $("#lDiv").append('<b>到' + end + '。</b>') $("#span" + j).append(str1); } } function showDRIVINGDetail(directionResult) { $("#lDiv").html(''); for (var j = 0; j < directionResult.routes.length && j < 3; j++) { var myRoute = directionResult.routes[j]; $("#lDiv").append('路线' + (j + 1) + '<br/>'); $("#lDiv").append('<b>从' + start + '出发。<b><br/>'); for (var i = 0; i < myRoute.legs[0].steps.length; i++) { var s = myRoute.legs[0].steps[i]; $("#lDiv").append(' ' + s.instructions + '<br/>'); $("#lDiv").append(' ' + s.distance.text + '-' + s.duration.text + '<br/>'); } $("#lDiv").append('<b>到' + end + '。</b><br/><br/>') } } function nearBySearch() { var referAddr = $("#referAddress").val(); if (referAddr.length > 0) { geocoder.geocode({ 'address': referAddr }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { deflocation = results[0].geometry.location; map.setCenter(deflocation); var queryAddr = $("#queryAddress").val(); var request = { name: queryAddr, location: deflocation, radius: '5000' }; var service = new google.maps.places.PlacesService(map); service.nearbySearch(request, callback); } }); } } function ShowInfoWindow() { } function callback(results, status) { $('#lDiv').html(""); if (status == google.maps.places.PlacesServiceStatus.OK) { //map.setCenter(results[0].geometry.location); deflocation = results[0].geometry.location; var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < results.length && i < 8; i++) { var place = results[i]; var marker = new google.maps.Marker({ map: map, icon: '/images/micon' + (i + 1) + '.png', position: place.geometry.location, zIndex: ++zindex }); attachInstructionText(marker, place.name); $("#lDiv").append('<a id="a' + i + '" href="javascript:void(0)" >' + arr[i] + ',' + place.name + '</a>' + '<input id="h' + i + '" type="hidden" value="' + place.name +'">' + '<br/>'); $("#a" + i).click(function () { var s = $("#" + $(this).attr("id").replace('a', 'h')).val().replace('(', '').replace(')', '').split(','); stepDisplay.setContent('' + s); var mk = markersArray[parseInt($(this).attr("id").replace('a', ''))]; stepDisplay.open(map, mk); mk.setZIndex(++zindex); }) bounds.extend(place.geometry.location); markersArray.push(marker); marker.setTitle(place.name); } if (results.length > 1) { map.fitBounds(bounds); } else { map.setCenter(results[0].geometry.location); map.setZoom(11); } } else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) { $("#lDiv").html($("#noneContent").html()) } else { //alert("查询时发生了错误: " + status); } } $(function () { initialize(); $("#searchCity").click(function () { deleteOverlays(); $('#lDiv').html("正在查询..."); PlaceSearch($("#cityName").val()); }); $("#searchBus").click(function () { deleteOverlays(); $('#lDiv').html("正在查询..."); calcRoute(); }); $("#searchSurround").click(function () { deleteOverlays(); $('#lDiv').html("正在查询..."); nearBySearch(); }); var input = document.getElementById("cityName"); var options = { bounds: map.center, types: ['establishment'] }; autocomplete = new google.maps.places.Autocomplete(input, options); input = document.getElementById("startAddress"); autocomplete = new google.maps.places.Autocomplete(input, options); input = document.getElementById("endAddress"); autocomplete = new google.maps.places.Autocomplete(input, options); input = document.getElementById("referAddress"); autocomplete = new google.maps.places.Autocomplete(input, options); }); </script> <style type="text/css"> .pac-container{width:600px;overflow:hidden} .pac-item{width:600px; overflow:hidden} </style> </head> <body> <h2> MapTools</h2> <div style="height: 100%;"> <div> <h3> 地址查询</h3> <label title="城市" for="cityName"> 城市</label> <input name="cityName" size="60" id="cityName" type="text" /> <input name="searchCity" id="searchCity" type="button" value="查询" /> <br /> <h3> <select id="tm"> <option value="bus">公交查询</option> <option value="driving">驾车查询</option> </select></h3> <label title="起始地址" for="startAddress"> 从</label> <input name="startAddress" size="60" id="startAddress" value="" type="text" /> <label title="终止地址" for="endAddress"> 到</label> <input name="endAddress" size="60" id="endAddress" value="" type="text" /> <input name="searchBus" id="searchBus" type="button" value="查询" /> <h3> 周边查询</h3> <label title="参照地址" for="referAddress"> 在</label> <input name="referAddress" size="60" id="referAddress" type="text" /> <label title="查询地址" for="queryAddress"> 附近查找</label> <input name="queryAddress" id="queryAddress" type="text" /> <input name="searchSurround" id="searchSurround" type="button" value="查询" /> </div> <br /> <div id="lDiv" style="width: 300px; height: 600px;overflow:auto; float: left"> </div> <div id="rDiv" style="width: 700px; height: 600px; border: 1; float: left"> </div> <div style="clear: both"> </div> <div id="warnings_panel"> </div> </div> <div id="noneContent" style="margin: 20;display:none"> 抱歉!未找到相关地点。 <br/>您可以: 看看输入的城市、街道和地点名称是否有错别字。 <br/>确认您的地址是否包含省、自治区、市、县、乡镇的名称。 <br/>试试去掉街道和街号后面过于冗长的部分。 </div> </body> </html>