Add a Marker to Google Map in Laravel 5.8

skipperhoa

Hòa Nguyễn Coder

Posted on October 9, 2019

Add a Marker to Google Map in Laravel 5.8

Today, I'm share example simple Add a Marker to Google Map in Laravel 5.8
Setup Laravel 5.8 version

composer create-project --prefer-dist laravel/laravel blog "5.8.*"

Enter fullscreen mode Exit fullscreen mode

Create Migration

php artisan make:migration create_boxmaps_table --create=boxmaps
Enter fullscreen mode Exit fullscreen mode

After creating, go to database / migrations to find newly created file and reconfigure as follows:

Schema::create('boxmaps', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    $table->string('description');
    $table->string('lng');
    $table->string('lat');
    $table->timestamps();
});

Enter fullscreen mode Exit fullscreen mode

Once the configuration is finished, run php artisan migrate to initialize the table boxmaps table in our database
Create Model in Laravel

php artisan make:Boxmap
Enter fullscreen mode Exit fullscreen mode

Create Authentication

php artisan make:Auth
Enter fullscreen mode Exit fullscreen mode

The purpose I ran the above command was to take advantage of the auth's layouts for ease of use
Create Mapbox Register
People go to the following link: https://docs.mapbox.com/mapbox-gl-js/api/ register, we just need to copy the link script and css of mapbox provided for us to attach to the file only, quite well is simple
Create View Blade
Create main.blade.php file in resources / views / layouts / main.blade.php
Continue to copy 2 links provided by mapbox, attach file main.blade.php

<!DOCTYPE html>
<html>
  <head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<script src="{{asset('js/app.js')}}" defer></script>
<link href="{{asset('css/app.css')}}" rel="stylesheet">
<script src="{{asset('js/jquery.min.js')}}"></script>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.css' rel='stylesheet' />
  </head>
  <body>
    <div >
        @yield('content')
    </div>
  </body>
<style>
        .mapboxgl-popup {
            max-width: 400px;
            font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
        }
</style>
@yield('script')
</html>
Enter fullscreen mode Exit fullscreen mode

Create a pages directory in the resources / views directory
Create the file google-map.blade.php in the path just created resources / views / pages
edit the file google-map.blade.php as follows:

@extends('layouts.main')
@section('script')
<script>
        mapboxgl.accessToken = 'pk.eyJ1Ijoic2tpcHBlcmhvYSIsImEiOiJjazE2MjNqMjkxMTljM2luejl0aGRyOTAxIn0.Wyvywisw6bsheh7wJZcq3Q';
        var map = new mapboxgl.Map({
          container: 'map',
          style: 'mapbox://styles/mapbox/streets-v11',
          center: [106.660172, 10.762622], //lng,lat 10.818746, 106.629179
          zoom: 7
        });
        var test ='<?php echo $dataArray;?>';  //ta nhận dữ liệu từ Controller
        var dataMap = JSON.parse(test); //chuyển đổi nó về dạng mà Mapbox yêu cầu

        // ta tạo dòng lặp để for ra các đối tượng
        dataMap.features.forEach(function(marker) {

            //tạo thẻ div có class là market, để hồi chỉnh css cho market
            var el = document.createElement('div');
            el.className = 'marker';

            //gắn marker đó tại vị trí tọa độ
            new mapboxgl.Marker(el)
                .setLngLat(marker.geometry.coordinates)
                .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
            .setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
                .addTo(map);
        });

    </script>
    <style>
        #map {
            width: 100%;
            height: 500px;
        }
        .marker {
            background-image: url('/images/point.png');
            background-repeat:no-repeat;
            background-size:100%;
            width: 50px;
            height: 100px;
            cursor: pointer; 
        }
</style>
@endsection
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-4">
            <h2>Google Map</h2>
            @if (session('success'))
                <div class="alert alert-success">
                    {{ session('success') }}
                </div>
            @endif
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
           <form action="{{route('google.map.store')}}" method="post" id="boxmap">
           @csrf
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" name="title" placeholder="Title" class="form-control"/>
                </div>
                <div class="form-group">
                    <label for="title">Description</label>
                    <input type="text" name="description" placeholder="Description" class="form-control"/>
                </div>
                <div class="form-group">
                    <label for="lat">lat</label>
                    <input type="text" name="lat" placeholder="lat" class="form-control"/>
                </div>
                <div class="form-group">
                    <label for="lng">lng</label>
                    <input type="text" name="lng" placeholder="lng" class="form-control"/>
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="Add Map" class="btn btn-success"/>
                </div>
            </form>
        </div>
        <div class="col-md-8">
            <h2>Show google Map</h2>
            <div id="map"></div>       
        </div>
    </div>
</div>
@endsection
Enter fullscreen mode Exit fullscreen mode

The code above I create a form to add the coordinates information and at the same time I receive data except controller-> view, so we can handle them.
Create Controller in Laravel

php artisan make:controller GoogleMapController  --resources
Enter fullscreen mode Exit fullscreen mode

Open the newly created GoogleMapController.php file and edit it as the code below, I have used the validation you created and imported into the file.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\FormMapRequest;
use App\Boxmap;
class GoogleMapController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $boxmap = Boxmap::all();

        $dataMap  = Array();
        $dataMap['type']='FeatureCollection';
        $dataMap['features']=array();
       foreach($boxmap as $value){
                $feaures = array();
                $feaures['type']='Feature';
                $geometry = array("type"=>"Point","coordinates"=>[$value->lng, $value->lat]);
                $feaures['geometry']=$geometry;
                $properties=array('title'=>$value->title,"description"=>$value->description);
                $feaures['properties']= $properties;
                array_push($dataMap['features'],$feaures);

       }
        return View('pages.google-map')->with('dataArray',json_encode($dataMap));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(FormMapRequest $request)
    {
       $validated = $request->validated();
       Boxmap::create($request->all());
       return redirect('/google-map')->with('success',"Add map success!");


    }
}
Enter fullscreen mode Exit fullscreen mode

Configuation Route

//web.php
Route::prefix('google-map')->group(function () {
    Route::get('/','GoogleMapController@index')->name('google.map.index');
    Route::post('/post','GoogleMapController@store')->name('google.map.store');
});
Enter fullscreen mode Exit fullscreen mode

Test Add Market Google Map in Laravel 5.8

php artisan serve
Enter fullscreen mode Exit fullscreen mode

We try to google search for a location and get the coordinates at that location try to see, his example is "Vung Tau" offline
add a market to google map in laravel 5.8 - hoanguyenit.com
add a market to google map in laravel 5.8 - hoanguyenit.com
add a market to google map in laravel 5.8 - hoanguyenit.com
Post:Add a Marker to Google Map in Laravel 5.8 or more post

💖 💪 🙅 🚩
skipperhoa
Hòa Nguyễn Coder

Posted on October 9, 2019

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

Sign up to receive the latest update from our blog.

Related