Home » Android » android – Flutter – Open Location in Maps

android – Flutter – Open Location in Maps

Posted by: admin June 15, 2020 Leave a comment

Questions:

Given lat and long.
Is there any fast/smart way to open maps google/apple in Flutter and head to directions ?

I’m using url_launcher for telephone calls, can i use the plugin to open link that open maps ?

_launchURL() async {
  const url = 'https://www.google.com/maps/place/Al+Duqqi,+Ad+Doqi,+Giza+Governorate/@31.0523046,32.2009323,17z/data=!3m1!4b1!4m5!3m4!1s0x1458413a996ec217:0x2411f6b62d93ccc!8m2!3d30.05237!4d31.2031598';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}
How to&Answers:

Yes you can do that using the url_launcher plugin. The following code will open Google Maps when the app is installed on the phone (otherwise it will open the browser):

void _launchMapsUrl(double lat, double lon) async {
  final url = 'https://www.google.com/maps/search/?api=1&query=$lat,$lon';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

Answer:

I created a plugin Map Launcher for that.

To find installed maps on a device you can use:

import 'package:map_launcher/map_launcher.dart';

final availableMaps = await MapLauncher.installedMaps;

And then launch by calling showMarker on it

await availableMaps.first.showMarker(
  coords: Coords(31.233568, 121.505504),
  title: "Shanghai Tower",
  description: "Asia's tallest building",
);

Or just check if map available and launch it if so

if (await MapLauncher.isMapAvailable(MapType.google)) {
  await MapLauncher.launchMap(
    mapType: MapType.google,
    coords: coords,
    title: title,
    description: description,
  );
}

Answer:

I used for this native method

try {
  await platform.invokeMethod('showLocation', [event.location[0], event.location[1], event.title]);
} on Exception catch (ex) {
  print('${ex.toString()}');
  ex.toString();
}

And in android package

class MainActivity : FlutterActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)
    MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
        if (call.method == "showLocation") {
            val args = (call.arguments) as List<Any>
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("geo:${args[0]}, ${args[1]}?z=23&q=${args[0]},${args[1]}(${args[2]})")))
            result.success(null)
        } else {
            result.notImplemented()
        }
    }
}

}