Google Maps API 方向服务显示重复的文本方向

Posted

技术标签:

【中文标题】Google Maps API 方向服务显示重复的文本方向【英文标题】:Google Maps API Directions Service Displaying Text Directions Repeating 【发布时间】:2016-07-16 00:18:59 【问题描述】:

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

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 函数时遇到问题。当我第一次搜索位置并单击“搜索按钮”时,什么也没有发生。第二次点击“搜索按钮”,在地图上成功绘制路线并显示路线,但路线显示两次(似乎路线是第一次点击计算的,但只有第二次点击是它们被显示)。如果我第三次搜索,则会添加第三组方向,并且会一遍又一遍地重复。

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

delete search_lat;
delete search_lng;

calculateAndDisplayRoute 函数的内部和末尾。没有运气。

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>

问题:如何在每次搜索期间使用一组坐标刷新方向?

【问题讨论】:

不要在每次调用getDirectionsByAddress时创建一个新的DirectionsRenderer-instance @Dr.Molle 谢谢。那么它会被放在函数之外呢?你能举个例子吗?再次感谢您的帮助 请提供一个Minimal, Complete, Tested and Readable example 来证明这个问题。 【参考方案1】: 在地理编码器返回结果之前,search_latsearch_lng 为 null。 地理编码器是异步的,直到您首次调用路线服务后,其结果才会返回。

提示是 javascript 控制台中的此错误:Uncaught TypeError: Cannot read property 'b' of null

将对路线服务的调用移动到地理编码器的回调函数中(数据存在的位置/时间)。

解决这个问题,并创建一个 DirectionsRenderer 实例,它对我有用。

proof of concept fiddle

代码 sn-p:

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 方向服务显示重复的文本方向的主要内容,如果未能解决你的问题,请参考以下文章

在 google maps api v3 中隐藏方向服务中的标记

Android Google Maps API v2 显示路线 [重复]

Google Maps JavaScript API v3 方向功能

将多个方向请求一起添加 Google Maps API

Google Maps API 标记点击事件未触发 [重复]

Google Maps API - 在单独的文本字段中显示可拖动标记 Lat 和 Lng [重复]