Share Location | How do i share current location in flutter

Published December 18, 2020


How do we share current location in flutter, do we have any way to share location?

Yes, in this post we are going to learn how to share location in flutter application.

To share location we are sending the Maps current location coordinate values and share method.

For this example we are using Maps Plugin to display Google Maps and Share plugin to share the content to other applications like whatsapp, Gmail, message etc...

 

If you are don't know how to load Google maps in flutter application then read Previous Post

 

Let's get started:

Step 1: Create Flutter Application

Step 2: Add Google Maps and Share intent plugins to pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  google_maps_flutter:
  share: ^0.6.5+4

 

Step 3: To use Google Maps we need to get a Google API key, For this, we need to create an application in Google Console and get an API key. Google Console

 

Step 4: Copy Google Maps key inside Manifest file.

 

<meta-data android:name="com.google.android.geo.API_KEY"
    android:value="MAPS_KEY"/>

 

Share Location FLutter

Step 5: Create dart file and add below code

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:share/share.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MapSample(),
    );
  }
}

class MapSample extends StatefulWidget {
  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  Completer<GoogleMapController> _controller = Completer();

  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );


  MapType mapTye = MapType.normal;
  Set<Marker> markerList=Set();
  Marker currentMArker;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    currentMArker=Marker(markerId: MarkerId("1"),position: _kGooglePlex.target);
    markerList.clear();
    markerList.add(currentMArker);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(title:Text("Google Maps"),actions: [
        Container(
          decoration:  BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8)),
              color: Colors.greenAccent,
                  shape: BoxShape.rectangle
              ),
          child: Padding(
            padding: const EdgeInsets.only(left:8.0),
            child: DropdownButton(
              style: TextStyle(color: Colors.black,fontSize: 20,),
                value: mapTye,
                items: [
                  DropdownMenuItem(
                    child: Text("Normal"),
                    value: MapType.normal,
                  ),
                  DropdownMenuItem(
                    child: Text("Hybrid"),
                    value: MapType.hybrid,
                  ),
                  DropdownMenuItem(
                      child: Text("Satellite"),
                      value: MapType.satellite
                  ),
                  DropdownMenuItem(
                      child: Text("Terrain"),
                      value:  MapType.terrain
                  )
                ],
                onChanged: (value) {
                  setState(() {
                    mapTye = value;
                  });
                }),
          ),
        ),
      ],),
      body: GoogleMap(
        mapType: mapTye,
        initialCameraPosition: _kGooglePlex,
        markers: markerList,
        onCameraIdle: (){
          setState(() {
            markerList.clear();
            markerList.add(currentMArker);
            print("Markers $currentMArker");
          });

        },
        onCameraMove: (campposition){
          currentMArker=Marker(markerId: MarkerId("1"),position: campposition.target);


        },
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _goToTheLake,
        label: Text('Share Location!'),
        icon: Icon(Icons.directions_boat),
      ),
    );
  }

  Future<void> _goToTheLake() async {
   if(currentMArker==null)
     {
       return;
     }
    Share.share('https://www.google.com/maps/search/?api=1&query=${currentMArker.position.latitude},${currentMArker.position.longitude}');

  }
}

 

Step 6: Now run the application

On Tap on share location button we are fetching the Maps current location coordinates and appending that coordinates to Google Location Search API and calling the Share Intent.

Share.share('https://www.google.com/maps/search/?api=1&query=${currentMArker.position.latitude},${currentMArker.position.longitude}');

 

Conclusion:

Bu this way we can share User Location to WhatsApp,Gmail,Facebook and etc... by share intent. The Location what we are sharing will be reading from Location Coordinates. In this Application we can also show Google maps in different style like Terrain style, Normal Style, satellite and Hybrid style.

 

Tags: Google Maps, Mutilple Markers, Share Location

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1145 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions