How to show user location accurately in Laravel

592 views Asked by At

I have a problem about showing user's location with latitude and longitude on map. After I host/deploy my project I noticed the location is wrong. It shows some place I don't even know probably my internet provider's location.

What I use in my Laravel project:

  • Leaflet.js
  • geoip

My Controller I want to show the map in my create.blade file:

//user's location 
private function getLocation(){
     //return location coordinate from user's ip
     return geoip()->getLocation($_SERVER['REMOTE_ADDR']);
}

//create
public function create($id, Request $request){
   $location = $this->getLocation();
return view('presence.create', compact(
            'location'
        ));
    }

I sceptical about $_SERVER['REMOTE_ADDR'] line, I'm not sure it shows true user's ip or it is my provider's ip

leaflet.js in my blade file:

<div id="map"></div>
<script>
    var map = L.map('map').setView([-6.297979, 106.922899], 10);

    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    //put user's latitude and longitude to marker 
    L.marker([ {{ $location->lat }}, {{ $location->lon }}]).addTo(map)
        .bindPopup('{{ auth()->user()->name }}')
        .openPopup();

    //destination marker
    var destination = L.marker([ -6.297979, 106.922899]).addTo(map)
        .bindPopup('Tujuan')
        .openPopup();
    destination._icon.classList.add("huechange");
    
    var circle = L.circle([-6.297979, 106.922899], {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5,
        radius: 20
    }).addTo(map);

</script>
0

There are 0 answers