JS+ google.maps.api 實現基本的導航功能

1、準備條件:javascript

1.谷歌地圖開發者文檔:https://developers.google.cn/maps/documentation/javascript/tutorialjava

2.申請一個API的Key。ide

 

2、如何實現(只提供JS代碼):google

1.先構造一張地圖。spa

2.進行地址解析3d

3.根據地址解析獲取到的座標進行請求服務獲取路線結果code

4.在地圖上繪製路線orm

5.路線顯示選擇blog

 

3、結果。事件

 4.源代碼。

  <script>
    var directions = new google.maps.DirectionsService();  //獲取路線請求的服務
    var renderer = new google.maps.DirectionsRenderer();   //路線顯示
 
    var map, transitLayer;
    var infowindow;
    var markersArray = [];
    var from
    var to;
    var from_g;
    var to_g;

    function initialize() {   //構造地圖
      var mapOptions = {
        zoom: 13,
        center: new google.maps.LatLng(40.7482333, -73.8681295),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      map = new google.maps.Map(document.getElementById('map'), mapOptions);

      google.maps.event.addDomListener(document.getElementById('go'), 'click',route); //獲取路線單擊事件

      transitLayer = new google.maps.TransitLayer();

      var control = document.getElementById('transit-wpr');
      map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);

      google.maps.event.addDomListener(control, 'click', function () {
        transitLayer.setMap(transitLayer.getMap() ? null : map);
      });

      geocoder = new google.maps.Geocoder(); //實例化地址解析

      //點擊地圖獲取座標
      google.maps.event.addListener(map, 'click', function (event) {
        placeMarker(event.latLng);
      });

    }


    function searchMap_from() {
      from = document.getElementById('from').value;
      codeAddress(from);
    }

    function searchMap_to() {
      to = document.getElementById('to').value;
      codeAddress(to);
    }
 
    function addDepart() {   //路線途徑點信息的添加
      var depart = document.getElementById('depart');
      for (var i = 0; i < 24; i++) {
        for (var j = 0; j < 60; j += 15) {
          var x = i < 10 ? '0' + i : i;
          var y = j < 10 ? '0' + j : j;
          depart.innerHTML += '<option>' + x + ':' + y + '</option>';
        }
      }
    }

    function handle() {   //地址解析獲取座標
      from = document.getElementById('from').value;
      to = document.getElementById('to').value;
      if (isNaN(from)) {

        var fn = function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
              from_g = results[0].geometry.location;
            }
          } else {
            from_g = from;
            alert("Geocoder failed due to: " + status);
          }

        }
        getGeocoder(from, fn)
      }

      if (isNaN(to)) {

        var fn = function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
              to_g = results[0].geometry.location;
            }
          } else {
            to_g = to;
            alert("Geocoder failed due to: " + status);
          }

        }
        getGeocoder(to, fn)
      }
    }

    function route() {
      var departure = document.getElementById('depart').value;
      var bits = departure.split(':');
      var now = new Date();
      var tzOffset = (now.getTimezoneOffset() + 60) * 60 * 1000;

      var time = new Date();
      time.setHours(bits[0]);
      time.setMinutes(bits[1]);

      var ms = time.getTime() - tzOffset;
      if (ms < now.getTime()) {
        ms += 24 * 60 * 60 * 1000;
      }

      var departureTime = new Date(ms);

      from_g = null;
      to_g = null;
      handle(); //獲取到座標
      preDrawRoute();

      function preDrawRoute() {
        if (!from_g || !to_g) {
          setTimeout(preDrawRoute, 10);
          return;
        }
        drawRoute();
      }

      function drawRoute() {  //路線請求內容
        var request = {
          origin: from_g,
          destination: to_g,
          travelMode: google.maps.DirectionsTravelMode.DRIVING,
          provideRouteAlternatives: true,
          transitOptions: {
            departureTime: departureTime
          }
        };

        var panel = document.getElementById('panel');
        panel.innerHTML = '';
        directions.route(request, function (response, status) {   //繪製路線
          if (status == google.maps.DirectionsStatus.OK) {
            renderer.setDirections(response);
            renderer.setMap(map);
            renderer.setPanel(panel);
          } else {
            renderer.setMap(null);
            renderer.setPanel(null);
          }

        });
      }

    }

    function placeMarker(location) {  //點擊地圖在地圖上某點顯示座標
      clearOverlays(infowindow); //清除地圖中的標記
      marker = new google.maps.Marker({
        position: location,
        map: map
      });
      markersArray.push(marker);
      //根據經緯度獲取地址
      if (geocoder) {
        geocoder.geocode({
          'location': location
        }, function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
              attachSecretMessage(marker, results[0].geometry.location, results[0].formatted_address);
            }
          } else {
            alert("Geocoder failed due to: " + status);
          }
        });
      }
    }
    //在地圖上顯示經緯度地址
    function attachSecretMessage(marker, piont, address) {
      var message = "<b>座標:</b>" + piont.lat() + "," + piont.lng() + "<br />" + "<b>地址:</b>" + address;
      var infowindow = new google.maps.InfoWindow({
        content: message,
        size: new google.maps.Size(50, 60)
      });
      infowindow.open(map, marker);
      if (typeof (mapClick) == "function") mapClick(piont.lng(), piont.lat(), address);
    }
    //刪除全部標記陣列中消除對它們的引用
    function clearOverlays(infowindow) {
      if (markersArray && markersArray.length > 0) {
        for (var i = 0; i < markersArray.length; i++) {
          markersArray[i].setMap(null);
        }
        markersArray.length = 0;
      }
      if (infowindow) {
        infowindow.close();
      }
    }

    //地址查詢
    function codeAddress(allAddress) {
      if (geocoder) {
        geocoder.geocode({
            'address': allAddress
          },
          function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              var beachMarker = new google.maps.Marker({
                map: map
              });
              map.setCenter(results[0].geometry.location);
              map.setZoom(15);
              beachMarker.setPosition(results[0].geometry.location); //顯示圖釘
              attachSecretMessage(beachMarker, results[0].geometry.location, results[0].formatted_address);

            } else {
              //alert("加載地圖失敗,緣由爲: "
              //    + status);
            }
          });
      }
    }

    function getGeocoder(allAddress, fn) {  //地址解析
      if (geocoder) {
        geocoder.geocode({
          'address': allAddress
        }, fn);
      }
    }
    google.maps.event.addDomListener(window, 'load', initialize);
  </script>
相關文章
相關標籤/搜索