Vipin Malik
Vipin Malik

Reputation: 105

How to add marker in the google map using flutter?

I am creating a nearby flutter app which shows restaurant around your location. i have found the nearby location but unable to add markers on the nearby coordinates.I want to know how to add markers to my location using google API and how to load the location from the list to my map.

void getData() async {
    http.Response response = await http.get(
        'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&key=API_KEY');

    if (response.statusCode == 200) {
      String data = response.body;
      var decodedData = jsonDecode(data);
      print(decodedData);
      List<String> names = [];
      List<double> lat = [];
      List<double> lng = [];
      for (var i = 0; i < 10; i++) {
        names.add(decodedData['results'][i]['name']);
        lat.add(decodedData['results'][i]['geometry']['location']['lat']);
        lng.add(decodedData['results'][i]['geometry']['location']['lng']);
      }
      print(names);
      print(lat);
      print(lng);
    }
  }



Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: GoogleMap(
                  initialCameraPosition: CameraPosition(
                    target: LatLng(-33.8670522, 151.1957362),
                    zoom: 14.4746,
                  ),
                  markers: Set<Marker>.of(markers.values),
                  onMapCreated: (GoogleMapController controller) {
                    _controller.complete(controller);
                  },
                ),
              ),
            ),

Upvotes: 2

Views: 10028

Answers (3)

zetsu010
zetsu010

Reputation: 84

Iterable markers = [];

// in GoogleMap use like this

GoogleMap(...
  markers: Set.from(markers),
),

// in function or where you want

Iterable _markers = Iterable.generate(list.length, (index) {
return Marker(
  markerId: MarkerId("marker$index"),
  position: list[index].position);
});
setState(() {
  markers = _markers;
});

Upvotes: 0

10101010
10101010

Reputation: 1821

Make sure you add your API_KEY. A working example of your requirement follows

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  LatLng latlng = LatLng(
    -33.8670522,
    151.1957362,
  );
  Iterable markers = [];

  @override
  void initState() {
    super.initState();

    getData();
  }

  getData() async {
    try {
      final response =
          await http.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&key=API_KEY');

      final int statusCode = response.statusCode;

      if (statusCode == 201 || statusCode == 200) {
        Map responseBody = json.decode(response.body);
        List results = responseBody["results"];

        Iterable _markers = Iterable.generate(10, (index) {
          Map result = results[index];
          Map location = result["geometry"]["location"];
          LatLng latLngMarker = LatLng(location["lat"], location["lng"]);

          return Marker(markerId: MarkerId("marker$index"),position: latLngMarker);
        });

        setState(() {
          markers = _markers;
        });
      } else {
        throw Exception('Error');
      }
    } catch(e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GoogleMap(
        markers: Set.from(
          markers,
        ),
        initialCameraPosition: CameraPosition(target: latlng, zoom: 15.0),
        mapType: MapType.hybrid,
        onMapCreated: (GoogleMapController controller) {},
      ),
    );
  }
}

markers

Upvotes: 4

key
key

Reputation: 1402

In the end you have to structure it yourself but it should look something like this

  final Set<Marker> _markers = {};

  setState(() {
  // add marker on the position
  _markers.add(Marker(
  // This marker id can be anything that uniquely identifies each marker.
  markerId: MarkerId(_lastMapPosition.toString()),
  position: _lastMapPosition,
  infoWindow: InfoWindow(
  // title is the address
  title: address.addressLine,
  // snippet are the coordinates of the position
  snippet: 'Lat: ${address.coordinates.latitude}, Lng: ${address
      .coordinates.longitude}',
  ),
  icon: BitmapDescriptor.defaultMarker,
  ));
  }

Upvotes: 0

Related Questions