PHP code example of doode / filament-map-picker

1. Go to this page and download the library: Download doode/filament-map-picker library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

doode / filament-map-picker example snippets



namespace App\Filament\Resources;
use Filament\Resources\Resource;
use Filament\Resources\Forms\Form;
use Filament\Forms\Components\{
    Actions,
    Actions\Action,
    Fieldset,
    FileUpload,
    Hidden,
    TextInput,
    Textarea,
};

use Doode\MapPicker\Fields\Map;
...

class FilamentResource extends Resource
{
    ...
    public static function form(Form $form)
    {
        return $form->schema([
            Map::make('map')
                ->columnSpanFull()
                ->showFullscreenControl()
                ->showZoomControl()
                ->draggable()
                ->zoom(10) // Not 
                            'name' => 'GoogleMap',
                            'url' => "google.maps.googleapis.com",
                            'minZoom' => 1,
                            'maxZoom' => 28,
                        ],
                        [
                            'name' => 'SatelliteMap',
                            'url' => "url_satellite",
                            'minZoom' => 1,
                            'maxZoom' => 28,
                        ]
                    ])
                    ->defaultBaseLayer('Standard')
                    ->overlayLayers([
                        [
                            'name' => 'Marine Charts',
                            'url' => "url_marine_charts",
                            'minZoom' => 1,
                            'maxZoom' => 18,
                            'opacity' => 0.5,
                            'visibleByDefault' => false
                        ],
                        // New options from version 1.6.2
                        [
                            'name' => 'Marker points or areas',
                            'url' => "api_url",
                            'type' => 'api',
                            'minZoom' => 1,
                            'maxZoom' => 18,
                            'attribution' => '',
                            'visibleByDefault' => false
                        ],
                        [
                            'name' => 'Cities',
                            'url' => asset('geojson/cities.geojson'),
                            'type' => 'geojson',
                            'minZoom' => 1,
                            'maxZoom' => 18,
                            'attribution' => '',
                            'visibleByDefault' => false
                        ]
                    ])
                
                // Location
                ->defaultLocation(latitude: 52.8027, longitude: -1.0546)
                ->liveLocation(true, true, 5000) // or simple use `false` to disable live
                ->showMyLocationButton()
                ->boundaries(true, 49.5, -11, 61, 2) // Example for United Kingdom
                ->rangeSelectField('distance')
                
                // Marker Configuration
                ->showMarker()
                ->markerColor("#22c55eff")
                ->clickable() // Click to set marker
                ->iconSize(32) // Icon size
                
                // GeoMan Toolbar
                ->geoManToolbar(true)
                ->geoManEditable(true)
                ->geoManPosition('topleft') // other options are: topright, bottomright and bottomleft
                ->drawCircleMarker(true)
                ->rotateMode(true)
                ->drawText(true)
                ->drawMarker(true)
                ->drawPolygon(true)
                ->drawPolyline(true)
                ->drawCircle(true)
                ->dragMode(true)
                ->cutPolygon(true)
                ->editPolygon(true)
                ->deleteLayer(true)
                ->setColor('#3388ff')
                ->setFilledColor('#cad9ec') // Color inside the shapes
                
                //State Management
                ->afterStateUpdated(function (callable $set, ?array $state): void {
                    $set('latitude', $state['lat']);
                    $set('longitude', $state['lng']);
                    $set('geomanbox', json_encode($state)); 
                })
                ->afterStateHydrated(function ($state, $record, callable $set): void {
                    $set('location', ['lat' => $record->latitude, 'lng' => $record->longitude]);
                    $set( 'geomanbox', json_decode(strip_tags($record?->geomanbox)) );
                })
           ]),
           
           // Field to store the geojson data
           Hidden::make('geomanbox')->id('geomanbox')
    }
    ...
}

// Starting from version 1.6.0           
// Map Picker allows you to upload a GeoJSON file, automatically reading and rendering all shapes on the map
// for a seamless and interactive mapping experience.
// Here is an example of how to use it.
FileUpload::make('file')
    ->acceptedFileTypes(['application/json', 'application/geo+json'])
    ->maxSize(1024)
    ->storeFiles(false) // Store file is not necessary
    ->afterStateUpdated(function ($state, callable $set, $livewire){
        if (!$state){ return; }
        $geojsonData = json_decode($state->get(), true);
        if (!$geojsonData) { return; }
        if (isset($geojsonData['type']) && $geojsonData['type'] === 'FeatureCollection') {
            $set('geom', json_encode($geojsonData['features']));
            $set('name', $geojsonData['name'] ?? $geojsonData['features'][0]['properties']['name'] ?? 'Name Unknown');
            $livewire->dispatch('loadGeoJsonDataFromFile', json_encode($geojsonData['features']));
        }
    }),

Map::make('location')
    ->showMarker(true)
    ->clickable(true)
    ->defaultLocation(latitude: 52.8027, longitude: -1.0546)
    ->zoom(12) // Not 

Fieldset::make('Location')
    ->schema([
        Select::make('membership_distance')
            ->enum(MembershipDistance::class)
            ->options(MembershipDistance::class)
            ->  ->detectRetina()
            ->defaultLocation(latitude: 40.4168, longitude: -3.7038)
            ->rangeSelectField('distance')
            ->setFilledColor('#cad9ec'),
            //->tilesUrl("https://tile.openstreetmap.de/{z}/{x}/{y}.png") //Not in use from version 1.6.0
    ])
    ->columns(1),

Map::make('location')
    ->liveLocation(true, true, 10000)  // Updates live location every 10 seconds
    ->showMarker()
    ->draggable()

Map::make('location')
    ->showMarker()
    ->boundaries(true,49,11.1,61.0,2.1) //Example for United Kingdom
    ->draggable()

Actions::make([
   Action::make('capture_map_image')
       ->hiddenLabel()
       ->icon('heroicon-m-camera')
       ->color('info')
       ->action(function (callable $get, $livewire) {
           $lat = $get('lat');
           $lon = $get('lon');

           if(!empty($lat) && !empty($lon)){
               $livewire->dispatch('captureMapImage');
           }
       })
   ])->columnSpan(1)

// web.php file
Route::post('/upload-map-image', [MapController::class, 'uploadMapImage'])->name('upload.map.image');

// MapController file or any name you want to use
// You can customise your controller to handle the temporary image file path in various ways,
// such as storing it in the session, updating a database record, moving the file, or implementing any other logic you image')) {
            $file = $request->file('map_image');
            $path = $file->store('maps');

            if($path){
                session(['uploaded_map_image_path' => $path]);
                return response()->json(['success' => true]);
            }
        }

        return response()->json([
            'error' => false,
            'message' => 'No image uploaded / Failed to remove transparency'
        ], 400);
    }
}


use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Actions;
use Filament\Support\Enums\VerticalAlignment;

Actions::make([
    Action::make('Set Default Location')
        ->icon('heroicon-m-map-pin')
        ->action(function (Set $set, $state, $livewire): void {
            $set('location', ['lat' => '52.8027', 'lng' => '-1.0546']);
            $set('latitude', '52.8027');
            $set('longitude', '-1.0546');
            $livewire->dispatch('refreshMap');
        })
])->verticalAlignment(VerticalAlignment::Start);


use Doode\MapPicker\Infolists\MapEntry;

public static function infolist(Infolist $infolist): Infolist
{
    return $infolist
        ->schema([
            MapEntry::make('location')
                ->showMarker()
                ->iconSize(32)
                ->showGeomanToolbar()
                ->markerColor("#22c55eff")
                ->showFullscreenControl()
                ->draggable(false)
                ->zoom(15)
                ->extraStyles(['min-height: 50vh','border-radius: 50px'])
                ->state(fn ($record) => ['lat' => $record?->latitude, 'lng' => $record?->longitude]),
            .....
        ]);
}

$table->double('latitude')->nullable();
$table->double('longitude')->nullable();

->afterStateHydrated(function ($state, $record, Set $set): void {
    $set('location', ['lat' => $record?->latitude, 'lng' => $record?->longitude]);
})

TextInput::make('latitude')->hidden(),
TextInput::make('longitude')->hidden()

class YourModel extends Model
{
    protected function location(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => [
                'latitude' => $attributes['latitude'],
                'longitude' => $attributes['longitude']
            ],
            set: fn (array $value) => [
                'latitude' => $value['latitude'],
                'longitude' => $value['longitude']
            ],
        );
    }
}

                   Map::make('location')
                       ->hiddenLabel()
                       ->columnSpanFull()
                       ->defaultLocation(latitude: 52.8027, longitude: -1.0546)
                       ->afterStateHydrated(function (callable $set, callable $get, $state, ?Model $record) {
                           if ($record) {
                               // Icon base64_encoded value
                               $icon = YourModel::find($record->databasefield)->base64_image;

                               $set('location', [
                                       'lat' => $record->lat,
                                       'lng' => $record->lon,
                                       'icon' => $icon //Insert this icon key with the value
                                   ]);
                           }
                       })
                       ->extraStyles(['min-height: 30vh', 'border-radius: 5px'])
                       ->liveLocation(false, false, 5000)
                       ->showMarker()
                       ->iconSize(32)
                       ->markerColor("#FF0000")
                       ->showGeomanToolbar(false)
                       ->showFullscreenControl(true)
                       ->showZoomControl()
                       ->draggable()
                       ->tilesUrl("https://tile.openstreetmap.de/{z}/{x}/{y}.png") // **Necessary from version below 1.6**
                       ->zoom(6)
                       ->detectRetina()
                       ->showMyLocationButton(false)
                       ->extraControl(['zoomDelta' => 1, 'zoomSnap' => 2]),

                    Select::make('category_id')
                        ->label('Category')
                        ->suffixIcon('heroicon-s-square-3-stack-3d')
                        ->options(function () {
                            return YourModel::where('is_active', true)->get()
                                ->mapWithKeys(function ($item) {
                                    return [
                                        $item->id =>
                                        "<div style='display: flex; align-items: center;'>
                                            <img src='{$item->base64_image}' alt='category_icon' style='width: 20px; height: 20px; margin-right: 8px;' />
                                            <span>{$item->name}</span>
                                        </div>",
                                    ];
                                })
                                ->toArray();
                        })
                        ->searchable()
                        ->allowHtml()
                        ->