DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

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) {

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: 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>
  <meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('', '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=''></script>
<link href='' rel='stylesheet' />
    <div >
        .mapboxgl-popup {
            max-width: 400px;
            font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
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:

        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)
                .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
            .setHTML('<h3>' + + '</h3><p>' + + '</p>'))

        #map {
            width: 100%;
            height: 500px;
        .marker {
            background-image: url('/images/point.png');
            width: 50px;
            height: 100px;
            cursor: pointer; 
<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') }}
            @if ($errors->any())
                <div class="alert alert-danger">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
           <form action="{{route('')}}" method="post" id="boxmap">
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" name="title" placeholder="Title" class="form-control"/>
                <div class="form-group">
                    <label for="title">Description</label>
                    <input type="text" name="description" placeholder="Description" class="form-control"/>
                <div class="form-group">
                    <label for="lat">lat</label>
                    <input type="text" name="lat" placeholder="lat" class="form-control"/>
                <div class="form-group">
                    <label for="lng">lng</label>
                    <input type="text" name="lng" placeholder="lng" class="form-control"/>
                <div class="form-group">
                    <input type="submit" name="submit" value="Add Map" class="btn btn-success"/>
        <div class="col-md-8">
            <h2>Show google Map</h2>
            <div id="map"></div>       
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();
       foreach($boxmap as $value){
                $feaures = array();
                $geometry = array("type"=>"Point","coordinates"=>[$value->lng, $value->lat]);
                $feaures['properties']= $properties;

        return View('')->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();
       return redirect('/google-map')->with('success',"Add map success!");

Enter fullscreen mode Exit fullscreen mode

Configuation Route

Route::prefix('google-map')->group(function () {
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 -
add a market to google map in laravel 5.8 -
add a market to google map in laravel 5.8 -
Post:Add a Marker to Google Map in Laravel 5.8 or more post

Top comments (1)

thanhloc253 profile image

Can you share this source code?