integrate Google Maps into a Laravel application using JavaScript

ashrakt_amin

ashrakt

Posted on May 6, 2024

integrate Google Maps into a Laravel application using JavaScript
  1. place controller
<?php

namespace App\Http\Controllers;

use App\Models\Place;
use Illuminate\Http\Request;

class PlaceController extends Controller
{
    public function index()
    {
        $places = Place::all();

        return view('places.index', compact('places'));
    }

    public function create()
    {
        return view('places.create');
    }

    public function store(Request $request)
    {
        // Validate the request data as per your requirements
        $validatedData = $request->validate([
            'name' => 'required',
            'latitude' => 'required',
            'longitude' => 'required',
        ]);

        Place::create($validatedData);

        return redirect()->route('places.index')->with('success', 'Location created successfully');
    }

    public function show(Place $place)
    {
        return view('places.show', compact('place'));
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. index blade
@extends('layouts.app')

@section('content')

<a href="{{ route('places.create') }}" class="btn btn-primary mt-5 ml-5">Add Location</a>

<div class="container d-flex justify-content-center">
    <table class="table mt-1" style="width:60%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Latitude</th>
                <th>Longitude</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($places as $place)
            <tr>
                <td>{{ $place->name }}</td>
                <td>{{ $place->latitude }}</td>
                <td>{{ $place->longitude }}</td>
                <td>
                    <a href="{{ route('places.show', $place->id) }}" class="btn btn-primary">View</a>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>
@endsection
Enter fullscreen mode Exit fullscreen mode
  1. create blade
@extends('layouts.app')

@section('content')
<h3 class="text-center m-3">Add Location</h3>

<div class="container">
    <form id="location-form" action="{{ route('places.store') }}" method="POST">
        @csrf
        <input type="hidden" name="latitude" id="latitude" required>
        <input type="hidden" name="longitude" id="longitude" required>

        <div class="form-group">
            <label for="place">Place</label>
            <input type="text" id="place" name="name" class="form-control" placeholder="Search for a place" required>
        </div>

        <button type="submit" class="btn btn-primary mb-3">Save</button>
    </form>

    <div id="map" style="height: 300px;"></div>

</div>

<script src="https://maps.googleapis.com/maps/api/js?key={{ env('GOOGLE_MAPS_API_KEY') }}&libraries=places&callback=initMap" async defer></script>
<script>
    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: 0,
                lng: 0
            },
            zoom: 2
        });

        var input = document.getElementById('place');
        var searchBox = new google.maps.places.SearchBox(input);

        map.addListener('bounds_changed', function() {
            searchBox.setBounds(map.getBounds());
        });

        var marker;

        searchBox.addListener('places_changed', function() {
            var places = searchBox.getPlaces();

            if (places.length === 0) {
                return;
            }

            var bounds = new google.maps.LatLngBounds();

            places.forEach(function(place) {
                if (!place.geometry) {
                    console.log("Returned place contains no geometry");
                    return;
                }

                if (marker) {
                    marker.setMap(null);
                }

                marker = new google.maps.Marker({
                    map: map,
                    position: place.geometry.location,
                    draggable: true
                });

                google.maps.event.addListener(marker, 'dragend', function(event) {
                    document.getElementById('latitude').value = event.latLng.lat();
                    document.getElementById('longitude').value = event.latLng.lng();
                });

                google.maps.event.addListener(map, 'click', function(event) {
                    marker.setPosition(event.latLng);
                    document.getElementById('latitude').value = event.latLng.lat();
                    document.getElementById('longitude').value = event.latLng.lng();
                });

                if (place.geometry.viewport) {
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });

            map.fitBounds(bounds);
        });
    }
</script>
@endsection
Enter fullscreen mode Exit fullscreen mode
  1. show blade
@extends('layouts.app')

@section('content')

<div class="container d-flex justify-content-center mt-5">
    <table class="table mt-3" style="width:50%">
        <tbody>
            <tr>
                <th>Name</th>
                <td>{{ $place->name }}</td>
            </tr>
            <tr>
                <th>Latitude</th>
                <td>{{ $place->latitude }}</td>
            </tr>
            <tr>
                <th>Longitude</th>
                <td>{{ $place->longitude }}</td>
            </tr>
        </tbody>
    </table>
    <div class="container d-flex justify-content-center mt-3">
        <div class="d-flex justify-content-center" id="map" style="height: 300px;width:50%;" data-latitude="{{ $place->latitude }}" data-longitude="{{ $place->longitude }}"></div>
    </div>
</div>

<script>
    function initMap() {
        var latitude = document.getElementById('map').dataset.latitude;
        var longitude = document.getElementById('map').dataset.longitude;
        var location = {
            lat: parseFloat(latitude),
            lng: parseFloat(longitude)
        };

        var map = new google.maps.Map(document.getElementById('map'), {
            center: location,
            zoom: 12
        });

        var marker = new google.maps.Marker({
            map: map,
            position: location
        });
    }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key={{ env('GOOGLE_MAPS_API_KEY') }}&callback=initMap" async defer></script>

@endsection
Enter fullscreen mode Exit fullscreen mode
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
ashrakt_amin
ashrakt

Posted on May 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About