Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all 3919 articles
Browse latest View live

Symfony make:entity annotation mapping error

$
0
0

I want to create a new entity in my ORO platform application by using the make:entity command from the MakerBundle.

I expect it to create an entity in my bundle Acme\Bundle\TestBundle which I set in my config_dev.yml by using:

maker:
    root_namespace: 'Acme\Bundle\TestBundle'

So I execute

bin/console make:entity Test

which returns

 ! [NOTE] It looks like your app may be using a namespace other than "Acme\Bundle\TestBundle".                 
 !                                                                                                                      
 !        To configure this and make your life easier, see:                                                             
 !        https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html#configuration                           

 created: src/Acme/Bundle/TestBundle/Entity/Test.php
 created: src/Acme/Bundle/TestBundle/Repository/TestRepository.php


 [ERROR] Only annotation mapping is supported by make:entity, but the                                                   
         <info>Acme\Bundle\TestBundle\Entity\Test</info> class uses a different format. If you would like   
         this command to generate the properties & getter/setter methods, add your mapping configuration, and then      
         re-run this command with the <info>--regenerate</info> flag.                                                   

I've tried to run the command once again, which works. But obviously this is not the way how it's meant to work. So how can I fix this mapping error?


Adding auth route to generate a JWT in OpenApi 3

$
0
0

I would like to achieve this kind of result with ApiPlatform and OpenApi V3 : screenchot of an old swagger displaying an auth route

I found this on an old SO question : How to add Login to swagger UI with API PLATFORM (symfony 4)?

The route is plugged onto a LexikJWT handler in my firewalls, from security.yaml. I managed to add a custom thing in the ItemOperations key of my resources.yaml but the thing doesn't seem to map properly to OpenApi.

Am I understanding something wrongly ?

Should I drop Lexik JWT bundle and do the auth in an other way ?

Am I missing something around schemes or yaml configuration ?

Thanks for your help !

Properly increment a twig value

$
0
0

I am trying to make a quizz using Symfony 4. I pass an array of Questions to my template, I tried to make a function i call when the user clicks on an answer, to load the next question.

here is what i tried :

function nextQuestion(){
                {% set i = i+1 %}
                var qst = document.getElementById("question");
                var ans1 =  document.getElementById("answer1");
                var ans2 =  document.getElementById("answer2");
                var ans3 =  document.getElementById("answer3");
                var ans4 =  document.getElementById("answer4");
                qst.innerHTML = "<p>{{qsts[i].getText}}</p>";
                ans1.innerHTML = "<p>{{qsts[i].getAnswers[0]}}</p>";
                ans2.innerHTML = "<p>{{qsts[i].getAnswers[1]}}</p>";
                ans3.innerHTML = "<p>{{qsts[i].getAnswers[2]}}</p>";
                ans4.innerHTML = "<p>{{qsts[i].getAnswers[3]}}</p>";
            }

the variable i is initialized outside the function, the problem is in {% set i = i+1 %}, it only works once then stops incrementing the value i.

i also tried making a javascript variable instead of a twig variable but i couldn't pass it to the twig array with the questions.

So how to properly do something like this ? And would learning a front end framework prevent this kind of difficulties ?

Thank you.

Symfony 4 post request too slow

$
0
0

It's my first time here :)

I'm making a website in Symfony 4. My problem is that forms take a long time to be submit. When I submit one of them, I wait between 5 and 20 seconds before the form ends.

I have this problem in local and prod. But in dev, forms submit instantly.

Prod and dev are in the same server (Debian 10, PHP 7.2, MariaDB 10.3) and have the same code, currently. I copied the prod database in dev to get the same amount of data.

When I watch the DOM Network of my browsers (Chrome or Firefox), i can see a post request that takes a long time to complete with 302 reponse.

How to setup access control for the user in symfony?

$
0
0

I have a users table where roles field contains ["ROLE_SUPERUSER"]

Now I have two Urls:

  • localhost:8000/api/en/login
  • localhost:8000/api/en/test

When the user successfully logins, it generate a cookie. How can set the access control to the second URL where if the cookie is not set then this URL is not allowed.

I have added following lines to the security.yaml file

access_control:
 - { path: ^/api/{locale}, roles: IS_AUTHENTICATED_ANONYMOUSLY }
 - { path: ^/api/{locale}, roles: ROLE_SUPERUSER}

But this didn't work.

Any help?

Symfony 4 Remember me not working without username

$
0
0

How can we configure Symfony 4 Remember me functionality to use email instead of username (as set by default) when creating the cookie and storing it in the browser?

My issue is that by using email to authenticate in S4, the cookie is created with the username instead of the email in its hash, stored in the browser but when S4 check my cookie to see if IS_AUTHENTICATED_REMEMBERED is true, it checks it against the username stored in the DB which doesn’t make sens. It should check it against email. So my remember me functionality doesn’t work. If I use the username to login, then it works, but that’s not what I want, I’d like my users to log in with their email address.

I’ve configurered the login to work with email instead of the default username behavior, but I can’t have remember me working that way.

I tried the following in my security.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt
    providers:
        user_provider:
            entity:
                class: App\Entity\User
                property: email
        in_memory: { memory: ~ }
        our_db_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern:    ^/
            http_basic: ~
            provider: our_db_provider
            anonymous: ~
            form_login:
                login_path: login
                check_path: login
                default_target_path: dashboard
                username_parameter: email
                password_parameter: password
                remember_me: true
            remember_me:
                secret:   '%kernel.secret%'
                lifetime: 31536000 # 1 week in seconds
                path: /
                domain: ~
                secure:   true
                name:     REMEMBERME
                remember_me_parameter: remember_me
                always_remember_me: true
            logout:
                path:  /logout
                target: /

but this doesn’t let you parameter what field remember is using to generate the hash stored in the cookie.

If you’ve managed to set up your login / authentication & remember me working with a field different than username, please share :)

UPDATE: I tried Ahmed answer with the following lines on services but it’s not working:

App\Security\TokenBasedRememberMeServices:
      decorates: Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices

it says You have requested a non-existent service "Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices”.

PHP twig foreach Bootstrap Modal needHelp

$
0
0

I'am doing a modal, the modal show the player informations. We have a list of players showed with a twig foreach in a page. When i click on a player, i want the informations of the player. I tried with a simple bootstrap modal but only the first player is working. I should to use a ajax request?

I have some errors, somebody can help me?

The template to modify:

<h1 class="monEffectif">Mon effectif</h1>

<div class="globalTable">

<div class="tableLeft">

 {% for trainer in trainers %}
 {% for team in trainer.teams %}

<h2  class="monEffectif">{{ team.name }}</h2>

  {% for category in categories %}

        <table class="table col-10 custom">
        <thead>
            <tr>
                <th>{{ category.Type }} </th> 
                <th>Contact</th>
            </tr>
        </thead>
        <tbody>

        {% for player in category.Person %}

               <tr>
                <td>
                <a href="{{ path('player_showOne', {'id': player.id}) }}" data-toggle="modal" data-target="#dataModal">{{ player.lastname }} {{ player.firstname }}</a>


          <!-- dataModal -->

    <div id="dataModal" class="modal fade">  
        <div class="modal-dialog">  
            <div class="modal-content">  
                <div class="modal-header"> 
                <h4 class="modal-title" id="modal-title">Profil du joueur</h4> 
                    <button type="button" class="close" data-dismiss="modal">&times;</button>  
                </div>  
                <div class="modal-body">  
                <div class="imageModal">
                    <img src="{{ player.picture }} alt="photo du joueur">
                    <p>{{ player.lastname }} {{ player.firstname }}</p>
                </div>

                <div class="blockModal">
                <div class="leftSide">
                    <p>Date de naissance: </p>
                    <p>Nationalité: </p>
                    <p>Adresse: </p>
                    <p>Code postal: </p>
                    <p>Ville: </p>
                    <p>Adresse mail: </p>
                    <p>Numéro portable: </p>
                </div>
                <div class="rightSide">
                    <p>{{ player.birthday|date("d/m/Y") }}</p>
                    <p>{{ player.nationality }}</p>
                    <p>{{ player.address }}</p>
                    <p>{{ player.postal }}</p>
                    <p>{{ player.city }}</p>
                    <p>{{ player.Email }}</p>
                    <p>(+33){{ player.mobilePhone }}</p>
                </div>
                </div>
                </div>  
                <div class="modal-footer">  
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>  
                </div>  
            </div>  
        </div>  
    </div>```

How to resolve ERR_ABORTED 404 (Not Found) with Webpack Encore

$
0
0

I'm using Symfony 4.4 for a project and yesterday I deployed the project on my server. This is the first time I'm using the package webpack encore. It's cannot find the app.js and runtime.js files and the different images files...

This is the error message :

GET SERVERPATH/public/public/build/app.8faa2907.css net::ERR_ABORTED 404 (Not Found)

GET SERVERPATH/public/public/build/runtime.01250581.js net::ERR_ABORTED 404 (Not Found)

GET SERVERPATH/images/usersAvatar/5e685c89938b9522796974.jpeg 404 (Not Found)

I don't understund why I've two times /public/ for the path.

This is my webpack.config.js file :

var Encore = require('@symfony/webpack-encore');
const CopyWebpackPlugin = require('copy-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('public/build')

    .addEntry('app', './assets/js/app.js')

    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

    .addPlugin(new CopyWebpackPlugin([
        {from: './assets/static/', to: 'static'}
    ]))

    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

Do you have an idea ?


Updating field inside a repository [closed]

$
0
0

I'm creating a CRON in my Symfony 4 App (command) to archive news that is older than 60 days. How should this be done?

My first instinct was to add a method to my NewsRepository to retrieve all news that needs to be archive and update their isArchived boolean method from false to true if it's the case.

Then, I had this idea of adding the logic for archiving the news inside the repository so that it's usable outside the Command. I could also put the logic (MySQL Updates) inside the Command and just have the ''find'' query inside the repository.

Which of these approaches is preferable, and why? Should my repository method be findNewsToArchive and do the update logic inside the command, or should it be archiveAllNewsThatNeedsToBeArchived and do all the logic in the repository?

How to find the good path for image with Webpack Encore and Symfony 4

$
0
0

I'm using Symfony 4.4 for a project and yesterday I deployed the project on my server. This is the first time I'm using the package webpack encore. Impossible to find the path for the images

This is the error message :

GET SERVERPATH/images/usersAvatar/5e685c89938b9522796974.jpeg 404 (Not Found)

This is my webpack.config.js file :

var Encore = require('@symfony/webpack-encore');
const CopyWebpackPlugin = require('copy-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('bui/build')
    .setManifestKeyPrefix('build/')


    .addEntry('app', './assets/js/app.js')

    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

    .addPlugin(new CopyWebpackPlugin([
        {from: './assets/static/', to: 'static'}
    ]))

    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

Do you have an idea ?

Select from junction table

$
0
0

everybody! What should I do if I need to make select from junction table?

For example, I develop project and I need to make chats between users. I have two entities: User and Chat, and many-to-many relation between them (accordingly, I have three tables: user, chat, chat_user). I try to get all chats, which user is member, and to get all users from these chats.

I made the following SQL query:S

SELECT *
FROM chat c
         INNER JOIN chat_user cu ON c.id = cu.chat_id
         INNER JOIN user u ON u.id = cu.user_id
WHERE c.id IN (SELECT chat_id
               FROM chat_user
               WHERE user_id = <idUser>);

But I don't know how to translate in DQL subquery SELECT chat_id FROM chat_user WHERE user_id = <idUser>, because a haven't additional entity for table chat_user.

And I tried to add entity ChatUser and get data in ChatRepository smt. like this:

public function getChatsData($idUser)
   {
       $subQuery = $this->getEntityManager()
           ->getRepository(ChatUser::class)
           ->createQueryBuilder('chus')
           ->select('chus.chat')
           ->andWhere('chus.user = :idUser')
           ->setParameter('idUser', $idUser)
       ;

       $qb = $this->createQueryBuilder('c');

       return $qb
           ->innerJoin('c.chatUsers', 'cu')
           ->addSelect('cu')
           ->innerJoin('cu.user', 'u')
           ->addSelect('u')
           ->innerJoin('c.messages', 'm')
           ->addSelect('m')
           ->andWhere('u.id = :idUser')
           ->andWhere($qb->expr()->in(
               'c.id',
               $subQuery->getQuery()->getResult()
           ))
           ->setParameter('idUser', $idUser)
           ->getQuery()
           ->getResult()
           ;
   }

but it doesn't work. I get error [Semantical Error] line 0, col 12 near 'chat FROM App\Entity\ChatUser': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

Have Doctrine standard tools for such tasks?

Symfony 4 : Unsezialise() , ["allowed_classes" => false] error

$
0
0

(My english are bad, hope you will understand)

Hello, I'm actualy developping an website with Synfony 4 and created an admin login. I used serialise and unserialise.

  /**
     * @inheritDoc
     */
    public function serialize()
    {
        // TODO: Implement serialize() method.
        return serialize([
            $this->id,
            $this->username,
            $this->password
        ]);
    }

    /**
     * @inheritDoc
     */
    public function unserialize($serialized)
    {
        // TODO: Implement unserialize() method.
        list(
            $this->id,
            $this->username,
            $this->password
            ) = $this->unserialize($serialized, ["allowed_classes" => false]);
    }

At the end $this->unserialize($serialized, ["allowed_classes" => false]); doesn't work because "Method call is provided 2 parameters, but the method signature uses 1 parameters" (Intellij IDEA) I don't understand what that means and don't find anything about that.

I think that the basics methods just want unserialize($serialized) or something like that but when I fill the form and send it nothing happens.

Thank you for your reply.

What is causing the expected literal error?

$
0
0

I have a query that has a syntax error. This is the error!

string(63) "[Syntax Error] line 0, col 57: Error: Expected Literal, got 'd'"

public function getDomain(string $country)
{
    try {
        return $this->createQueryBuilder('d')
            ->where(':country NOT IN (d.blocked_countries)')
            ->setParameter('country', $country)
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult()
            ;
    } catch (\Exception $exception) {
        return $exception->getMessage();
    }
}

Update Symfony 4 to 5 DatetimeType validation error [duplicate]

$
0
0

I have this Symfony 4.3.11 API rest application :

Here is my post request body:

{
    "publicationDate": "2019-03-13"
}

Entity :

   /**
     * @var \DateTimeImmutable
     *
     * @ORM\Column(type="datetime_immutable")
     *
     * @Assert\NotBlank(message="required.field")
     * @Assert\Date(message="invalid.date")
     */
    private $publicationDate;

MyEntityType :

    $builder
       ->add('publicationDate', DateTimeType::class, [
            'input'           => 'datetime_immutable',
            'widget'          => 'single_text',
            'format'          => 'yyyy-MM-dd',
            'invalid_message' => 'invalid.date',
        ]);

The Post Submit data looks like :

object(App\Entity\MyEntity)[3996]
  private 'id' => null
  private 'publicationDate' => 
    object(DateTimeImmutable)[5718]
      public 'date' => string '2019-03-13 00:00:00.000000' (length=26)
      public 'timezone_type' => int 3
      public 'timezone' => string 'Europe/Paris' (length=12)

And this works fine.

But now, I've a basic Symfony 5.0.5 app with the same Entity. The form type is slightly different (the html5 option should be disabled) :

MyEntityType :

    $builder
       ->add('publicationDate', DateTimeType::class, [
            'input'           => 'datetime_immutable',
            'html5'           => false,
            'widget'          => 'single_text',
            'format'          => 'yyyy-MM-dd',
            'invalid_message' => 'invalid.date',
        ]);

The Post Submit data is exactly the same as above.

But when submitting, I've a validation error :

array (size=1)
  'publicationDate' => 
    array (size=1)
      0 => string 'This value should be of type string.'

Has anything changed in datetimetype between S4 and S5 ?

PHP - Symfony 4 - API Platform - Custom operation

$
0
0

Using SF4 & Api platform : I would like to have a route for performing a random computation, and returning result to the client.. this seems to be simple
However I am not able to do it easily with custom operations

Here it is what I have done

I have my entity, for request & reponse, using normalization to have field only in request, and not in response
And I have my Controller with my custom operation + the corresponding route only for collection (as I don't have any id) in yaml in the api_platform/resources.yaml file
The controller is taking the entity in input and responding with it, hydrated by the result

I am getting the error :

2018-08-18T16:22:42+02:00 [critical] Uncaught PHP Exception ApiPlatform\Core\Exception\InvalidArgumentException: "Unable to generate an IRI for the item of type "App\Entity\Computation"" at /dev/git/app-api/vendor/api-platform/core/src/Bridge/Symfony/Routing/IriConverter.php line 127

But I think this is when the server is serializing the reponse, as the computation is performed (log inside are printed)

Entity\Computation.php :

class Computation
{
/**
 * @var double  you input
 *
 * @Assert\NotBlank
 * @Groups({"read","write"})
 */
public $input;

/**
 * @var double the result
 *
 * @Groups({"read"})
 */
public $result;
}

Controller\ComputationController.php :

class ComputationController
{
    private $service;

    public function __construct(MyService $service)
    {
        $this->service= $service;
    }

    public function __invoke(Position $data): Response
    {
        $this->service->compute($data);
        return $data;
    }
}

api_platform/resources.yaml :

resources:
  App\Entity\Computation:
    itemOperations: {}
    collectionOperations:
      compute:
        method: 'POST'
        path: '/compute'
        controller: 'App\Controller\ComputationController'
    attributes:
      normalization_context:
        groups: ['read']
      denormalization_context:
        groups: ['write']

Can someone help me with it ?
Thanks !


how to get image data

$
0
0

I want get image data to crop and after then save

<?php

    namespace App\Controller;

    use App\Entity\Services;
    use App\Form\ServicesType;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Routing\Annotation\Route;
    use Symfony\Component\HttpFoundation\File\Exception\FileException;
    use Symfony\Component\HttpFoundation\File\UploadedFile;

    class CreateServiceController extends AbstractController
    {
        /**
         * @Route("/create/service", name="create_service")
         */
        public function index(Request $request)
        {

            $service = new Services();
            $form = $this->createForm(ServicesType::class, $service);
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {

                $service = $form->getData();
                $service->setCreated(new \DateTime('now'));

                /** @var UploadedFile $imagereFile */
                $imageFile = $form->get('image')->getData();

                if ($imageFile) {
                    $originalFilename = pathinfo($imageFile->getClientOriginalName(), PATHINFO_FILENAME);

                    $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
                    $newFilename = $safeFilename.'-'.uniqid().'.'.$imageFile->guessExtension();

                    try {
                        $imageFile->move(
                            $this->getParameter('image_directory'),
                            $newFilename
                        );

//problem here
                        $croped = \imagecrop( $this->getParameter('image_directory').$newFilename, ['x' => 0, 'y' => 0, 'width' => 100, 'height' => 100]);
                        imagejpeg($croped, $this->getParameter('image_directory').$newFilename, 75);
                    } catch (FileException $e) {
                        // ... handle exception if something happens during file upload
                    }
                    $service->setImage($newFilename);
                }

                // ... perform some action, such as saving the task to the database
                // for example, if Task is a Doctrine entity, save it!
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($service);
                $entityManager->flush();

                return $this->redirectToRoute('services');
            }

            return $this->render('update_service/index.html.twig', [
                'form' => $form->createView(),
            ]);
        }
    }

I have this code but it does not work

Warning: imagecrop() expects parameter 1 to be resource, string given

//problem here

$croped = \imagecrop( $this->getParameter('image_directory').$newFilename, ['x' => 0, 'y' => 0, 'width' => 100, 'height' => 100]);

imagejpeg($croped, $this->getParameter('image_directory').$newFilename, 75);

} catch (FileException $e) {

// ... handle exception if something happens during file upload

}

$service->setImage($newFilename);

}

Mixing positional and keyed arguments in service definition, using YAML

$
0
0

When configuring a service using XML, we can do the followin:

<service id="foobar" class="App\Foobar" public="false" abstract="true">
       <argument type="service" id="doctrine" />
       <argument>null</argument>
       <argument type="service" id="logger" on-invalid="ignore" />
       <argument key="$bombastic" type="service" id="bombastic.service" on-invalid="ignore" />
</service>

The first three arguments are positional (the first three arguments in the constructor), and the last one is keyed to the parameter name. Since the actual service has 5 arguments, the fourth argument is left undefined so it can be defined by a service that extends the foobar service.

Which is very nice.

In YAML the documentation shows how to use keyed arguments like this:

App\Updates\SiteUpdateManager:
        arguments:
            $someService: '@manager'

and positional arguments like this:

App\Updates\SiteUpdateManager:
        arguments:
            - '@manager'

But I'd like to do the same as the above XML configuration, but using YAML (because all the service configuration for this application is already in YAML, and I would not want to add a single XML configuration file just for this service).

How can I combine the two styles with YAML configuration?

Building an Point of Interest system with different comment types

$
0
0

I am building a system for POIs. We want to give the owner the possibility to add different types of comments/votes to a POI.

Like a harbour would have: Does it have W-LAN? (BOOL, once per POI) Whats the W-LAN password? (text, once per POI) Rate the hygiene rooms (vote (1-5), once per user)

I don't know, how to realize that in Symfony with the Entities.

Kind regards Henning

Are queries/commands objects mandatory on DDD with CQRS?

$
0
0

im working on a system built following DDD and some CQRS patterns written in symfony. Normally on a Query endpoint, the controller receives a request, and it uses an adapter service to build a query object and send it to the application layer.

Up to here everything is normal. But on a GetAll endpoint, functional wise I dont seem to require any request object (as i always return an array with all elements). Because of this, the questions seems like:

  • Should i keep receiving a request and convert it into an empty query object just to cover the DDD/CQRS?
  • Could I just call directly the application layer from my controller with no query params and just handle the response?

Thanks!

HERE maps for JavaScript API: How to calculate route?

$
0
0

I wanna implement in my project option to draw route on the map using HERE maps api, I read documentation and saw few examples and if I implement it all global and push static route to calculate distance like that:

    const platform = configPlatform();
    const defaultLayers = configLayers();
    var markers = [];
    var map = new H.Map(
    document.getElementById('mapContainer'),
    defaultLayers.vector.normal.map,
    {
      zoom: 10,
    }
    );

    var mapEvents = new H.mapevents.MapEvents(map);
    var behavior = new H.mapevents.Behavior(mapEvents);
    var icon  = setCustomMarker();

    const lineString = new H.geo.LineString();
    var polyline;
    var routingService = platform.getRoutingService();
    var routingParameters = {
    'mode': 'fastest;car',
    'waypoint0': 'geo!50.1120423728813,8.68340740740811',
    'waypoint1': 'geo!52.5309916298853,13.3846220493377',
    'representation': 'display'
    };

    routingService.calculateRoute(routingParameters, success => {
    console.log(success);
    });

It works fine, but I wanna do everything in functions (instantiate platform must be global and it's ok). First of all I wanna by navigator configure center of map (current user position) and next by event listener give user possibility to add markers to map and it all works but if I wanna next push data to routing service and calculate route between markers and whole distance I get following error:

Uncaught (in promise) TypeError: c is not a function at eval(eval at (mapsjs-core.js:70), :64:238)

Even if I just call method routingService.calculateRoute() inside eventlistener I get the same error.It looks like something in calculateRoute function must be instantiate in time map loading because it works ok when I calculateRoute next to loading map but if I use that function I listener It doesn't work. Somebody had any idea how to make it possible to run this method in listener (instantiate globally routing service doesn't help) ??

Viewing all 3919 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>