2016-07-16 2 views
-1

Я использую Google Maps JavaScript API для отображения маршрутов и текстовые направления:Google Maps API Directions Service Отображение текста Направления Повторяющиеся

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> 

Here is a picture of the repeating directions. I only want one set of directions to show for each search

Вопрос: Как я могу сделать так, что направления обновляется с одним набором координат во время каждого поиска?

+1

Не создавать новый DirectionsRenderer инстанции каждый раз, когда вы называете 'getDirectionsByAddress' –

+0

@ Dr.Molle Спасибо. Значит, он будет помещен вне функции? Можете ли вы показать пример, пожалуйста? Еще раз спасибо за помощь. – cpcdev

+0

Просьба представить [Минимальный, завершенный, проверенный и читаемый пример] (http://stackoverflow.com/help/mcve), который демонстрирует проблему. – geocodezip

ответ

1
  • search_lat и search_lng являются нулевыми, пока геокодер не возвращает результаты.
  • геокодер является асинхронным, его результаты не возвращаются до тех пор, пока вы не поместите первый вызов в службу маршрутов.

намек эта ошибка в консоли JavaScript: Uncaught TypeError: Cannot read property 'b' of null

Переместить вызов службы направления в функцию обратного вызова для геокодера (где/когда существует данные).

Исправьте это и создайте один экземпляр DirectionsRenderer, и он работает для меня.

proof of concept fiddle

фрагмент кода:

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>

+0

Спасибо, хороший сэр – cpcdev

Смежные вопросы