上一篇咱們講到google給的示例代碼中實現了軌跡動畫,惋惜軌跡是從一開始就畫出來的,不能知足動態生成軌跡的要求,那咱們該咋麼辦呢?
別擔憂,googleAPI爲咱們想到了這個問題,雖然他沒有直接提到這種軌跡的demo,可是給咱們提供了不少的小例子,好比動態畫點,動態生成連線,動態更換圖標等的小例子,廢話很少說,先給出演示效果
javascript
那麼如何實現上面的動態效果呢,先給出我參考的例子
https://developers.google.com/maps/documentation/javascript/examples/polyline-complex?hl=zh-cn
可是有這個例子還不夠,示例實現了點擊畫線的功能,可是如何讓這些點每隔一段時間出現一個點呢?我使用了js的sleep方法,固然js沒有這個函數,因此間接調用了js的setTimeout()函數,代碼以下:html
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Complex Polylines</title> <style> html,body,#map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"> </script> <script> var neighborhoods = [new google.maps.LatLng(52.511467, 13.447179), new google.maps.LatLng(52.549061, 13.422975), new google.maps.LatLng(52.497622, 13.396110), new google.maps.LatLng(52.517683, 13.394393)]; var poly; var map; var markers = []; var lastIndex=-1; var iterator = 0; //小車圖標 var icon1 = 'image/1.jpg'; //軌跡點圖標 var icon2 = 'image/2.jpg'; function initialize() { var mapOptions = { zoom : 16, // Center the map on Chicago, USA. center : new google.maps.LatLng(parseFloat(52.511467, 13.447179) }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); var polyOptions = { strokeColor : '#000000', strokeOpacity : 1.0, strokeWeight : 3 }; poly = new google.maps.Polyline(polyOptions); poly.setMap(map); drop(); } //此處調用了setTimeout函數,i*2000是指距離第一次執行的時間 function drop() { for (var i = 0; i < neighborhoods.length; i++) { setTimeout(function() { addMarker(); }, i * 2000); } } function addMarker() { var path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(neighborhoods[iterator]); if (iterator > 0) { markers[iterator - 1].setIcon(icon2); } neighborhoods[iterator] // Add a new marker at the new plotted point on the polyline. markers.push(new google.maps.Marker({ position : neighborhoods[iterator], title : '#' + path.getLength(), map : map, icon : icon1 })); map.panTo(neighborhoods[iterator]); map.setCenter iterator++; } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas"></div> </body> </html>
好的,如今咱們實現了動畫軌跡功能,那麼如何給每一個軌跡點添加點擊事件顯示信息呢?請繼續關注個人下一篇博文 googleAPI點擊顯示窗口java