Skip to content
Advertisement

Laravel livewire – how to pass geo coordinates of user to livewire component

I am trying to send geo coordinates (latitude and longitude) of user to a livewire component to load nearby places. However I am unable to send it because they are javascript variables. Question is how do I send a javascript variable to a livewire component?

Here is what I have done so far.

# home.blade.php

@extends('layouts.app')

@section('content')
    <script>
        var latitude;
        var longitude;
        navigator.geolocation.getCurrentPosition(
            function success(pos) {
                var loc = pos.coords;
                latitude = loc.latitude;
                longitude = loc.longitude;
            }, 
            function error(err) {
                // console.warn(`ERROR(${err.code}): ${err.message}`);
                $.getJSON('https://ipinfo.io/geo', function(response) { 
                    var loc = response.loc.split(',');
                    latitude = parseFloat(loc[0]);
                    longitude = parseFloat(loc[1]);
                });
            }, options
        );
    </script>
    @livewire('nearby')
@endsection
@livewireScripts
# Nearby.php 

namespace AppHttpLivewire;

use LivewireComponent;
use LivewireWithPagination;
use AppListing;

class Nearby extends Component
{
    use WithPagination;

    public function render()
    {
        $listings = Listing::paginate(9);
        return view('livewire.nearby', [
            'listings' => $listings
        ]);
    }
}
# nearby.blade.php - livewire blade

<div class="relative bg-gray-50 px-4 sm:px-6 lg:px-8">
    <div class="relative max-w-6xl mx-auto">
        <div class="mt-12 grid gap-5 max-w-lg mx-auto lg:grid-cols-3 lg:max-w-none">
            @foreach($listings as $listing)
                @include('components.listing',['listing'=>$listing])
            @endforeach
        </div>
        <div class="text-center mx-auto mt-3">
            {{ $listings->links() }}
        </div>
    </div>
</div>

Advertisement

Answer

You’ll need to emit an event globally from you script. like this:

 //emit this event inside your success function. pass latitude and longitude with the event 

  window.livewire.emit('set:latitude-longitude', latitude, longitude) 

After that you can listen to this event from your livewire component class like this:

  protected $listeners = [
        'set:latitude-longitude' => 'setLatitudeLongitude'
    ];

Then set your passed lat long using setLatitudeLongitude function inside your livewire component class.

public function setLatitudeLongitude($latitude, $longitude) 
{
   $this->latitude = $latitude;
   $this->longitude = $longitude;
}

Let me know if you need further explanation 🙂

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement