Google Maps API路线服务显示重复的文字路线 [英] Google Maps API Directions Service Displaying Text Directions Repeating

查看:107
本文介绍了Google Maps API路线服务显示重复的文字路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Maps JavaScript API来显示路线和文本方向:

I'm using the Google Maps JavaScript API to display routes and text directions:

JS:

var geocoder;
var map;
var search_lat;
var search_lng;

function initMap() {

    var myLatLng = {
        lat: 38.5803844, 
        lng: -121.50024189999999
    };

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      center: myLatLng,
    });

    geocoder = new google.maps.Geocoder();

    document.getElementById('search_button').addEventListener('click', function() {
      getDirectionsByAddress(geocoder, map);
    });

    var locations = <?php echo json_encode($locations_array); ?>;

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {

        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][5], locations[i][6]),
            animation: google.maps.Animation.DROP,
            icon: icon_image,
            map: map
        });
    }

}

function getDirectionsByAddress() {

    // GET THE SEARCH ADDRESS

    var address = document.getElementById('address').value;
    console.log('search address: ' + address);

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            search_lat = results[0].geometry.location.lat();
            search_lng = results[0].geometry.location.lng();
            console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });

    // INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE 

    var directionsDisplay = new google.maps.DirectionsRenderer;
    var directionsService = new google.maps.DirectionsService;

    directionsDisplay.setMap(map);
   directionsDisplay.setPanel(document.getElementById('directions'));

    calculateAndDisplayRoute(directionsService, directionsDisplay);

    // CHECK THE MODE OF TRAVEL 

    document.getElementById('mode').addEventListener('change', function() {
      calculateAndDisplayRoute(directionsService, directionsDisplay);
    });

    // CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVEL

    function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
        var selectedMode = document.getElementById('mode').value;
        directionsService.route({
          origin: {lat: search_lat, lng: search_lng},
          destination: {lat: 38.5803844, lng: -121.50024189999999},
          travelMode: google.maps.TravelMode[selectedMode]
        }, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
    }

}

我在使用getDirectionsByAddress函数时遇到了麻烦.当我搜索位置并第一次单击搜索按钮"时,什么也没有发生.在搜索按钮"的第二次单击上,成功在地图上绘制了路线并显示了方向,但是方向显示了两次(似乎方向是在第一次单击时计算的,但只有在第二次单击时才计算)他们正在显示).如果我第三次搜索,则会遵循第三组指示,并且会一遍又一遍地重复.

I'm having trouble with the getDirectionsByAddress function. When I search a location and click the "search button" the first time, nothing happens. On the second click of the "search button", the route is drawn successfully on the map and the directions are displayed, however the directions are displayed twice (it seems the directions were calculated on the first click, but only on the second click are they being displayed). If I search a third time, the third set of directions are tacked on and this repeats over and over.

似乎我需要在每次搜索期间重置lat和lng值.我试过了:

It seems I need to reset the lat and lng values during each search. I tried:

delete search_lat;
delete search_lng;

calculateAndDisplayRoute函数的内部和结尾.没有运气.

inside and at the end of the calculateAndDisplayRoute function. No luck.

HTML:

<div id="map"></div>

<div id="directions">

    <h3>Directions</h3>

</div>

<div class="search_block">

    <input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" />

</div>

<div class="search_block">    

    <select name="travel_mode" id="mode">
        <option>DRIVING</option>
        <option>WALKING</option>
        <option>BICYCLE</option>
        <option>TRANSIT</option>
    </select>

</div>

<div class="search_block">

    <button id="search_button" onclick="getDirectionsByAddress();">Search</button>

</div>

问题:如何做到这一点,以便在每次搜索过程中使用一组坐标刷新方向?

Question: How can I make it so the directions are refreshed with a single set of coordinates during each search?

推荐答案

  • search_latsearch_lng为空,直到地理编码器返回结果为止.
  • 地址解析器是异步的,直到您对路线服务进行首次调用后,其结果才会返回.
    • search_lat and search_lng are null until the geocoder returns results.
    • the geocoder is asynchronous, its results don't come back until after you place the first call to the directions service.
    • 一个提示是javascript控制台中的此错误:Uncaught TypeError: Cannot read property 'b' of null

      a hint is this error in the javascript console: Uncaught TypeError: Cannot read property 'b' of null

      将对路线服务的调用移动到地址解析器的回调函数中(数据存在/存在的地方).

      Move the call to the directions service into the callback function for the geocoder (where/when the data exists).

      解决此问题,并创建DirectionsRenderer的单个实例,并且对我有用.

      Fix that, and create a single instance of the DirectionsRenderer and it works for me.

      概念证明小提琴

      代码段:

      google.maps.event.addDomListener(window, "load", initMap);
      var geocoder;
      var map;
      var search_lat;
      var search_lng;
      var directionsDisplay;
      var directionsService;
      
      function initMap() {
      
        var myLatLng = {
          lat: 38.5803844,
          lng: -121.50024189999999
        };
      
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: myLatLng,
        });
        directionsDisplay = new google.maps.DirectionsRenderer;
        directionsService = new google.maps.DirectionsService;
      
      
        geocoder = new google.maps.Geocoder();
      
        document.getElementById('search_button').addEventListener('click', function() {
          getDirectionsByAddress(geocoder, map);
        });
      
        var locations = []; //<?php echo json_encode($locations_array); ?>;
      
        var infowindow = new google.maps.InfoWindow();
      
        var marker, i;
      
        for (i = 0; i < locations.length; i++) {
      
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][5], locations[i][6]),
            animation: google.maps.Animation.DROP,
            icon: icon_image,
            map: map
          });
        }
      
      }
      
      function getDirectionsByAddress() {
      
        // GET THE SEARCH ADDRESS
      
        var address = document.getElementById('address').value;
        console.log('search address: ' + address);
      
        geocoder.geocode({
          'address': address
        }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            search_lat = results[0].geometry.location.lat();
            search_lng = results[0].geometry.location.lng();
            console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
            calculateAndDisplayRoute(directionsService, directionsDisplay);
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      
        // INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE 
      
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directions'));
      
      
      
        // CHECK THE MODE OF TRAVEL 
      
        document.getElementById('mode').addEventListener('change', function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        });
      
        // CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVEL
      
        function calculateAndDisplayRoute(directionsService, directionsDisplay) {
          console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
          var selectedMode = document.getElementById('mode').value;
          directionsService.route({
            origin: {
              lat: search_lat,
              lng: search_lng
            },
            destination: {
              lat: 38.5803844,
              lng: -121.50024189999999
            },
            travelMode: google.maps.TravelMode[selectedMode]
          }, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
              directionsDisplay.setDirections(response);
            } else {
              window.alert('Directions request failed due to ' + status);
            }
          });
        }
      
      }

      html,
      body,
      #map {
        height: 100%;
        width: 100%;
        margin: 0px;
        padding: 0px
      }

      <script src="https://maps.googleapis.com/maps/api/js"></script>
      <div id="directions">
      
        <h3>Directions</h3>
      
      </div>
      
      <div class="search_block">
      
        <input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" value="San Franscisco, CA" />
      
      </div>
      
      <div class="search_block">
      
        <select name="travel_mode" id="mode">
          <option>DRIVING</option>
          <option>WALKING</option>
          <option>BICYCLE</option>
          <option>TRANSIT</option>
        </select>
      
      </div>
      
      <div class="search_block">
      
        <button id="search_button" onclick="getDirectionsByAddress();">Search</button>
      
      </div>
      <div id="map"></div>

      这篇关于Google Maps API路线服务显示重复的文字路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆