Laravel livewire - 如何将用户的地理坐标传递给 livewire 组件

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

我正在尝试将用户的地理坐标(纬度和经度)发送到 livewire 组件以加载附近的地点。但是我无法发送它,因为它们是 javascript 变量。问题是如何将 javascript 变量发送到 livewire 组件?

这是我到目前为止所做的。

# 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 App\Http\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Listing;

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>

您需要从您的脚本全局发出一个事件。像这样:

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

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

之后,您可以像这样从 livewire 组件 class 收听此事件:

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

然后使用 livewire 组件中的 setLatitudeLongitude 函数设置您传递的经纬度 class。

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

如果您需要进一步解释,请告诉我 :)