Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> Zwrócenie wartości z funkcji
john_doe
post 23.05.2020, 08:19:13
Post #1





Grupa: Zarejestrowani
Postów: 873
Pomógł: 25
Dołączył: 24.07.2005

Ostrzeżenie: (0%)
-----


Hej, uzywam google do wyznaczenia odleglosci.

  1.  
  2. function calculateDistance(origin, destination) {
  3. var service = new google.maps.DistanceMatrixService();
  4. service.getDistanceMatrix(
  5. {
  6. origins: [origin],
  7. destinations: [destination],
  8. travelMode: google.maps.TravelMode.DRIVING,
  9. unitSystem: google.maps.UnitSystem.METRIC,
  10. avoidHighways: false,
  11. avoidTolls: false
  12. }, callback
  13. );
  14. }
  15.  
  16. function callback(response, status) {
  17. if (status != google.maps.DistanceMatrixStatus.OK) {
  18. console.log(err);
  19. } else {
  20. var origin = response.originAddresses[0];
  21. var destination = response.destinationAddresses[0];
  22. if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
  23. console.log("nie ma drog pomiedzy"
  24. + origin + " and " + destination);
  25. } else {
  26. var distance = response.rows[0].elements[0].distance;
  27. var distance_value = distance.value; // w metrach
  28. var distance_text = distance.text; // np. 2,4 km
  29. var distanceKm = distance_text.substring(0, distance_text.length - 3);
  30. console.log("Odległość: " + distance_text + " lub " + distance_value/1000 + " lub " + distanceKm);
  31. }
  32. }
  33. }
  34.  


Chcialbym z tego zwrocic po prostu wartosc dystansu i uzyc go gdzies indziej.
Call do google jest asynchroniczny, probowalem przypisywac wynik do zmiennej globalnej bez skutku...
Go to the top of the page
+Quote Post
viking
post 23.05.2020, 08:41:09
Post #2





Grupa: Zarejestrowani
Postów: 6 365
Pomógł: 1114
Dołączył: 30.08.2006

Ostrzeżenie: (0%)
-----


Poczytaj o await i promise.


--------------------
Go to the top of the page
+Quote Post
miccom
post 23.05.2020, 09:09:14
Post #3





Grupa: Zarejestrowani
Postów: 493
Pomógł: 8
Dołączył: 7.07.2007
Skąd: Tychy

Ostrzeżenie: (0%)
-----


Ja u mnie wykorzystuję taki kod, wywołuję tak:

  1. <div id="inputs">
  2. <form action="" onsubmit="initMap(); return false;">
  3. <input type="text" id="adres" placeholder="( np. warszawa, puławska 19 ) "/><br>
  4. <input type="submit" value="Oblicz odległosć" /> <br><br>
  5. </form>
  6. </div>
  7. <div id="output"></div>
  8. </div>
  9. <div id="map"></div>
  10. function initMap() {
  11. var bounds = new google.maps.LatLngBounds;
  12. var markersArray = [];
  13. var origin = 'Główna 31, Tychy';// tutaj musisz podać swój adres jeśli potrzebujesz do wyświetlenia
  14. if(document.getElementById("adres").value == ''){
  15. var destination = 'Główna 31, Tychy';
  16. alert('musisz podać adres docelowy');
  17. exit();
  18. }else{
  19. var destination = document.getElementById("adres").value;
  20. };
  21. var destinationIcon = 'https://www.google.com/intl/en_ALL/mapfiles/dd-end.png';
  22. var destinationTitle = 'A tutaj się zatrzymujemy!';
  23. var originIcon = 'https://www.google.com/intl/en_ALL/mapfiles/dd-start.png';
  24. var originTitle = 'Stąd wyruszamy :)';
  25. $('#map').css('width','400px').css('height', '400px');
  26. var map = new google.maps.Map(document.getElementById('map'), {
  27. center: {lat: 50.108138, lng: 19.0400068}, // tutaj pokazujesz mapkę na której google rozrysuje trasę
  28. zoom: 12
  29. });
  30. var geocoder = new google.maps.Geocoder;
  31. var service = new google.maps.DistanceMatrixService;
  32. service.getDistanceMatrix({
  33. origins: [origin],
  34. destinations: [destination],
  35. travelMode: google.maps.TravelMode.DRIVING,
  36. unitSystem: google.maps.UnitSystem.METRIC,
  37. avoidHighways: true,
  38. avoidTolls: true
  39. }, function(response, status) {
  40. if (status !== google.maps.DistanceMatrixStatus.OK) {
  41. alert('Error was: ' + status);
  42. } else {
  43. var originList = response.originAddresses;
  44. var destinationList = response.destinationAddresses;
  45. var outputDiv = document.getElementById('output');
  46. outputDiv.innerHTML = '';
  47. deleteMarkers(markersArray);
  48.  
  49. var showGeocodedAddressOnMap = function(asDestination) {
  50. var icon = asDestination ? destinationIcon : originIcon;
  51. var title = asDestination ? destinationTitle : originTitle;
  52. return function(results, status) {
  53. if (status === google.maps.GeocoderStatus.OK) {
  54. map.fitBounds(bounds.extend(results[0].geometry.location));
  55. markersArray.push(new google.maps.Marker({
  56. map: map,
  57. position: results[0].geometry.location,
  58. icon: icon,
  59. title : title
  60.  
  61. }));
  62. } else {
  63. if( status === 'ZERO_RESULTS' && document.getElementById("adres").value!= '' ){
  64. alert('Geolokalizator nie potrafi odnaleźć wpisanej miejscowości :( <br> Wpisz poprawną miejscowość');
  65. }
  66. }
  67. };
  68. };
  69.  
  70. for (var i = 0; i < originList.length; i++) {
  71. var results = response.rows[i].elements;
  72. geocoder.geocode({'address': originList[i]},
  73. showGeocodedAddressOnMap(false));
  74. for (var j = 0; j < results.length; j++) {
  75. geocoder.geocode({'address': destinationList[j]},
  76. showGeocodedAddressOnMap(true));
  77. outputDiv.innerHTML += 'odległość: ' + results[j].distance.text;
  78. $('#stronger').remove();
  79. }
  80. }
  81. }
  82. }
  83. });
  84. }
  85.  
  86. function deleteMarkers(markersArray) {
  87. for (var i = 0; i < markersArray.length; i++) {
  88. markersArray[i].setMap(null);
  89. }
  90. markersArray = [];
  91. }
  92. </script>
  93. <script async defer
  94. src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB3xxTXcVYShuoufkT1tV6L55C0_K0tMzw"><!-- tutaj musisz dać swój klucz API -->
  95. </script>


Ten post edytował miccom 23.05.2020, 09:21:17


--------------------
Jeśli pomogłem- kliknij POMÓGŁ-przyda się ;)- jeśli piszę bzdury- pisz pod postami. Poprawię się.
PISZĘ POPRAWNIE PO POLSKU!
Go to the top of the page
+Quote Post
john_doe
post 24.05.2020, 11:10:21
Post #4





Grupa: Zarejestrowani
Postów: 873
Pomógł: 25
Dołączył: 24.07.2005

Ostrzeżenie: (0%)
-----


@miccom może nie podawaj swojego klucza.

@viking dzięki.

napisałem coś co działa ale ... gdyby ktoś zaproponował inną wersję, inne wywołanie może, brakuje pewnie w sumie try/catch

Kod
function fetchDistance(origin, destination) {
            return new Promise(function(resolve, reject) {
                var service = new google.maps.DistanceMatrixService();
                service.getDistanceMatrix(
                {
                    origins: [origin],
                    destinations: [destination],
                    travelMode: google.maps.TravelMode.DRIVING,
                    unitSystem: google.maps.UnitSystem.METRIC,
                    avoidHighways: false,
                    avoidTolls: false
                },
                function(resp, status) {
                    if (status !== google.maps.DistanceMatrixStatus.OK) {
                        response = reject(status);
                    } else {
                        response = resolve(resp.rows[0].elements[0].distance.value);
                    }
                });
            });
        }
        async function getDistanceInKmAsync(start, end){
            const result = await fetchDistance(start, end);
            return result / 1000;
        }


a używam tak
Kod
getDistanceAsync(ORIGIN_ADDRESS, destinationAddress).then(result => {
            if(result <= <jakis_tam)
            {
                  // ...
            }
        });


Ten post edytował john_doe 24.05.2020, 11:11:34
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 29.03.2024 - 13:32