• JS+ google.maps.api 实现基本的导航功能


    一、准备条件:

    1.谷歌地图开发者文档:https://developers.google.cn/maps/documentation/javascript/tutorial

    2.申请一个API的Key。

     

    二、如何实现(只提供JS代码):

    1.先构造一张地图。

    2.进行地址解析

    3.根据地址解析获取到的坐标进行请求服务获取路线结果

    4.在地图上绘制路线

    5.路线显示选择

    三、结果。

     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>
  • 相关阅读:
    线段树专辑——hdu 1698 Just a Hook
    bool树的计算
    线段树专辑—— hdu 2795 Billboard
    数据库索引技术聚集索引和非聚集索引介绍(二)
    数据库索引技术—索引介绍 (一)
    AJAX核心对象 XMLHttpRequest 对象使用详解 (二)
    AJAX核心对象 XMLHttpRequest 对象使用详解 (一)
    输入框的提示信息(获得焦点和失去焦点时显示提示信息)
    不管你今天做了多少,加一点亮点总结今天的得分就是1.01。
    新情况——需要按照这个规定堆
  • 原文地址:https://www.cnblogs.com/kacy/p/11068157.html
Copyright © 2020-2023  润新知