O
O
olymp2017-07-04 00:55:22
JavaScript
olymp, 2017-07-04 00:55:22

Javascript how to pass a value from a function?

I've been scratching my head for the second week already...
I'm trying to implement building routes on Wordpress from a geolocation point to an accommodation facility.
Initially, the Plugin did not have the ability to implement routing, I have to finish it and ask for the help of experts!
What I have:

if (navigator.geolocation) { //Проверка, поддерживает ли браузер геолокацию
  	 navigator.geolocation.getCurrentPosition(function (position) {      //This gets the
  

   var propsAjaxURL = services_vars.ajaxurl;
   var propsSecurity = $('#securityAppMap').val();

     var latitude = position.coords.latitude;                    //users current
     var longitude = position.coords.longitude;                 //location
     var coords = new google.maps.LatLng(latitude, longitude); //Создаеем переменную для координат карты
          
          
      $.ajax({
                          type: 'POST',
                          dataType: 'json',
                          url: propsAjaxURL,
                          data: {
                              'action': 'reales_get_single_property',
                              'single_id': $('#single_id').val(),
                              'security': propsSecurity
                          },
                          success: function(data) {
                              var singlePosition = new google.maps.LatLng(data.props[0].lat, data.props[0].lng);
                          	

                          	


                              var styledMapType = new google.maps.StyledMapType(styles, {
                                  name : 'Styled'
                              });
                              map.mapTypes.set('Styled', styledMapType);
                              map.getStreetView().setOptions(panoramaOptions);

                              if(data.getprops === true) {
                                  
                                  map.setCenter(singlePosition);
                                  map.setZoom(parseInt(services_vars.zoom));

                                  addMarkers(data.props, map);
                              }

                              setPOIControls(map, singlePosition);
                          },
                          error: function(errorThrown) {
 
                          }
      });
                      

     var directionsService = new google.maps.DirectionsService();
     var directionsDisplay = new google.maps.DirectionsRenderer();
     var propsAjaxURL = services_vars.ajaxurl;
     var propsSecurity = $('#securityAppMap').val();
     var end = '53.085622, 70.307219';
           	


     var mapOptions = //Sets map options
     {
       zoom: 15,  //Наборы изменяют масштаб карты (0-21)
       center: coords, //увеличьте масштаб пользовательского местоположения
       mapTypeControl: true, //позволяет Вам выбирать тип карты, например, карту или спутник
       name : 'Styled',
       navigationControlOptions:
       {
         style: google.maps.NavigationControlStyle.SMALL //наборы на карту размер средств управления, например, увеличение масштаба изображения
       },
       mapTypeId: google.maps.MapTypeId.ROADMAP //тип наборов карты: ROADMAP, SATELLITE, HYBRID, TERRIAN
    };

     map = new google.maps.Map( /*создаем переменную Карты*/ document.getElementById("mapSingleView"), mapOptions /*Создает новую карту, используя переданные дополнительные параметры в mapOptions параметре.*/);
     var styledMapType = new google.maps.StyledMapType(styles, {
                    name : 'Styled'
                });

     directionsDisplay.setMap(map);
     directionsDisplay.setPanel(document.getElementById('panel'));
     var request = {
       origin: coords,
       destination: end,
       travelMode: google.maps.DirectionsTravelMode.DRIVING
     };
              
     directionsService.route(request, function (response, status) {
       if (status == google.maps.DirectionsStatus.OK) {
         directionsDisplay.setDirections(response);
       }
     });
   });
 }

I’m trying to display the value out of place , but I can’t transfer the value from another function - it’s given as an example that the route is built if you set the coordinates manually, if you specify the value , the map dies ... For example , I displayed, on the print screen, the result that the route is laid from the point And to the point 53.085622, 70.307219. The marker is also displayed with the correct location:var end = '53.085622, 70.307219';var end = singlePosition;function(data)
var end = '53.085622, 70.307219';var end = singlePosition;
0f96efc281bc4c2a98ccbb694ff0bbe1.jpg
var end = '53.085622, 70.307219';
var singlePosition = new google.maps.LatLng(data.props[0].lat, data.props[0].lng);

Is it possible to derive values var end = singlePosition;​​from another function? how to replace point B (coordinates) with value var end = singlePosition;
What am I doing no so???

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kovalsky, 2017-07-04
@olymp

You can simply build the route not immediately, but only after the request is executed:

$.ajax({
    ...
    success: function(data) {
        var singlePosition = new google.maps.LatLng(data.props[0].lat, data.props[0].lng);
        var request = {
            origin: coords,
            destination: singlePosition,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
       directionsService.route(...);
       ...
    },
    ...
});

S
Stalker_RED, 2017-07-04
@Stalker_RED

Javascript how to pass a value from a function?

Short answer: no way.
You are using destination: endbefore the ajax request has been processed.
What am I doing no???
Trying to work with complex stuff like googlemaps instead of learning the basics.
For two weeks it was quite possible to read about the scope of variables , returnand asynchronous calls .
Can be rewritten using callbacks or promises, as shown by Nikita Polevoy

A
Alexander Morgunov, 2017-07-04
@toruk0109

Here you can display the necessary data from AJAX, but only through a JSON object. You can copy it like this JSON.parse(JSON.stringify()). But do not forget that the AJAX callback function will come when the server receives a response, until then the program will execute the code following the AJAX (read about asynchrony and callback functions).
Therefore, it is better to perform all operations with data that will come from the server inside this callback. Otherwise, the card will "lay down" at any convenient and inconvenient time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question