Flutter Google Maps. Displaying style. How can I get this working? - google-maps

Due to a change in Google maps API to Widget-based and some sort of change to flutter, I'm receiving the following error:
Error: The method 'setMapStyle' isn't defined for the class 'GoogleMapController'.
I'm trying to load a custom style for my map from either .json or .txt. Here's my code:
SizedBox(
width: MediaQuery.of(context)
.size
.width, // or use fixed size like 200
height: 250,
child: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
),
oncreate and style:
void _onMapCreated(GoogleMapController controller) async {
Completer<GoogleMapController> _controller = Completer();
mapController = controller;
_setStyle(controller);
}
void _setStyle(GoogleMapController controller) async {
String value = await DefaultAssetBundle.of(context)
.loadString('assets/map_style.text');
controller.setMapStyle(value);
}
Anyone know how to get around this? :/

I have used this method and it worked.
onMapCreated: (GoogleMapController controller) {
controller.setMapStyle(Utils.mapStyles);}
i saved the stylr in a dart file as
class Utils {
static String mapStyles = '''[
{
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
}
]
},
{
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#616161"
}
]
},
.......
]''';
}

Related

How to add marker in the google map using json API in flutter?

I'm trying to add marker to my map based on the json API (EventData) by using http request. When I run my code the map does not show the marker. I think I am not accessing the list correctly. I want just to use these parameters: GPSPoint_lat , GPSPoint_lon and Address from EventData. can someone help me?
This is my json :
{
"Account": "",
"Account_desc": "",
"TimeZone": "GMT+00:00",
"DeviceList": [
{
"Device": "v19",
"Device_desc": "541266 DACIA NOIR",
"VehicleID": "",
"State": "62467",
"LastNotifyText": "",
"LastTimestamp": "1618683994",
"LastGPSTimestamp": 1618700203,
"Icon": "",
"DeviceCode": "tk12x",
"lastEngineHours": 4.5025,
"FuelLevel": 0.0,
"FuelTotal": "0.0 %",
"simPhoneNumber": "0607250761",
"EventData": [
{
"Device": "v19",
"Timestamp": 1618700203,
"Timestamp_date": "2021/04/17",
"Timestamp_time": "22:56:43",
"StatusCode": 62467,
"StatusCode_hex": "0xF403",
"StatusCode_desc": "Moteur OFF",
"GPSPoint": "35.74512,-5.85550",
"GPSPoint_lat": 35.74512,
"GPSPoint_lon": -5.85550,
"Speed_kph": 0.0,
"Speed": 0.0,
"Speed_units": "Km/H",
"Heading": 0.0,
"Heading_desc": "N",
"Altitude_meters": 0.0,
"Altitude": 0,
"Altitude_units": "meters",
"Odometer_km": 22438.364,
"Odometer": 22438.364,
"Odometer_units": "Distance en Kilomètre",
"Geozone": "",
"Geozone_index": 0,
"Address": "Tanger, 90045, Maroc",
"City": "Tanger",
"PostalCode": "90045",
"DigitalInputMask": 62467,
"DriverID": "",
"EngineHours": 4.50,
"acceleration": 0.00,
"brakeGForce": 0.00,
"EngineCoolantTemperature_C": 0.0,
"EngineCoolantTemperature": 32.0,
"EngineCoolantTemperature_units": "F",
"ThermoAverage_C": 0.0,
"ThermoAverage": 32.0,
"ThermoAverage_units": "F",
"EngineFuelUsed_Liter": 0.0,
"EngineFuelUsed": 0.0,
"EngineFuelUsed_units": "Litre",
"Index": 0
}
]
}
],
"consomFuelL": 0.0,
"consomFuelPr": "0.0 %",
"debug": "",
"maxspeed": 0.0,
"KM": 22129.80960258997,
"KMtotal": 22129.80960258997,
"minStop": 0,
"minOn": 0,
"minMarche": 0,
"Costfuel": 0.0
}
My code :
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
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: Maps (title: 'Flutter Demo Home Page'),
);
}
}
class Maps extends StatefulWidget {
#override
_MapsPageState createState() => _MapsPageState();
}
class _MapsPageState extends State<Maps> {
String data;
var superheros_length;
String ValRet;
int index;
#override
void initState() {
// TODO: implement initState
super.initState();
// setCustomMarker();
getData();
}
Set<Marker> _markers = {};
//worked
void _onMapCreated(GoogleMapController controller) async{
final googleOffices = await getData();
setState(() {
for (final dnn in googleOffices.jsonDecode(data)['DeviceList']) {
_markers.clear();
_markers.add(
Marker(markerId: MarkerId(dnn.jsonDecode(data)['DeviceList']['Device']),
position: LatLng(35.77561, -5.80351),
// icon: mapMarker,
infoWindow: InfoWindow(
title: dnn.jsonDecode(data)['DeviceList']['Device'],
snippet: dnn.jsonDecode(data)['DeviceList'][index]['address']
)
)
);
}
});
}
getData() async {
const googleLocationsURL = 'myAPIPrivate';
// Retrieve the locations of Google offices
final response = await http.get(googleLocationsURL);
if (response.statusCode == 200) {
data =response.body;
superheros_length= jsonDecode(data)['DeviceList'];
print (superheros_length.length);
} else {
throw HttpException(
'Unexpected status code ${response.statusCode}:'
' ${response.reasonPhrase}',
uri: Uri.parse(googleLocationsURL));
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
// backgroundColor: Colors.green[700],
),
body:
GoogleMap(
// mapType: _currentMapType,
onMapCreated: _onMapCreated,
markers: _markers,
initialCameraPosition: CameraPosition(
target: const LatLng(35.77561,-5.80351),
// target: _center,
// target: const LatLng(0,0),
zoom: 11.0,
),
// markers: _markers.values.toSet(),
),
),
);
}
}
error:
There are a few things that should probably be changed in the code.
var superheros_length; is misleading, I thought it was an integer at first, but based on your getData() function, it's a map. So, first off change it to:
List<Map<String, dynamic>> super_heros_length;
I would change the onMapCreated function to be something like this:
void _onMapCreated(GoogleMapController controller) async{
await getData();
_markers.clear();
for (final dnn in super_heros_length) {
setState(() {
_markers.add(
Marker(markerId: MarkerId(dnn['Device']),
position: LatLng(dnn["EventData"][0]["GPSPoint_lat"], dnn["EventData"][0]["GPSPoint_lon"]),
// icon: mapMarker,
infoWindow: InfoWindow(
title: dnn['Device'],
snippet: dnn["EventData"][0]['address']
)
)
);
});
}
}
To access the lat, based on your json, you have to use it like this:
["DeviceList"][0]["EventData"][0]["GPSPoint_lat"]
But since you are already accessing ["DeviceList"] and assigning it to superheroes_length, you don't have to repeat yourself, and use the code posted here, and update on what happens. Also post what errors you are recieving. You were also clearing your markees for every time you iterate in your for-loop, this way, if you had multiple markers, only the last marker will show, because every time you add a new marker, you were clearing everything before it, this is why I put it outside the loop.

Adding MarkerClustererPlus to existing Google Maps API embedded code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm looking to add clustering to a google Maps API embed that I have on a webflow website. Is anyone able to explain how I would implement this ( https://codelabs.developers.google.com/codelabs/maps-platform-101-js#5 ). I'm not sure what to do in step one when it states 'Import the marketcluster' with it being an embed. Is it even possibly with this solution?
Here's the current set up... https://jsfiddle.net/geocodezip/nz14hubc/1/
// Variables for Google maps
var map, mapElem, markerImg, infoWindow, marker;
var markers = [], infoWindows = [],
races = [{lat: 40.7127753, lng: -74.0059728, url:""},
{lat: 40.735657, lng:-74.1723667, url:""}];
var mapOptions = {
mapTypeId: 'roadmap',
//zoom: 13,
//scrollwheel: false,
styles: [
{
"featureType": "administrative",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#444444"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"color": "#f2f2f2"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "all",
"stylers": [
{
"saturation": -100
},
{
"lightness": 45
}
]
},
{
"featureType": "road.highway",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"color": "#2bb0e6"
},
{
"visibility": "on"
}
]
}
]
};
function initialize() {
markerImg = {
url:'https://uploads-ssl.webflow.com/5f58a4616a9e71d63ca059c8/5fa18680b95c219254ad0c9c_place-marker.png',
size: new google.maps.Size(46, 57),
anchor: new google.maps.Point(23, 54),
}
// Display a map on the page
mapElem = document.getElementById('map_canvas');
map = new google.maps.Map(mapElem, mapOptions);
map.setTilt(45);
// Loop through our array of races
for(i = 0; i < races.length; i++) {
var race = races[i];
// Generate an infowindow content for the marker
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(
'<div class="bg-race"</div>' +
'<p>'+race.name+'<br>Next race: '+race.date+'</p>' +
' Race wesbsite '
);
infoWindows.push(infoWindow);
// Place a marker on the map
createMarker(race.lat, race.lng, i);
}
// Center the map fitting all markers on the screen
fitToMarkers();
}
function createMarker(x, y, i) {
marker = new google.maps.Marker({
map: map,
icon: markerImg,
position: new google.maps.LatLng(x,y),
title: races[i].name
});
marker._index = i;
markers.push(marker);
// Click event on marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// Close last opened infowindow if any
if(infoWindow) infoWindow.close();
// Open clicked infowindow
infoWindow = infoWindows[i];
infoWindow.open(map, marker);
}
})(marker, i));
}
function fitToMarkers() {
map.setZoom(13);
var bounds = new google.maps.LatLngBounds();
for(var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
map.setZoom(13); // zoom out when done so markers on the top can be seen
}
/*
// When Webflow has loaded,
Webflow.push(function() {
// Resize event
$(window).resize(function() {
// Do nothing if mobile
if($(window).width() < 768) return;
// Resize map if function is defined
if(typeof mapResize === 'function') mapResize();
});
});
*/
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map_canvas {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initialize&libraries=&v=weekly"
defer
></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
This tutorial: Marker Clustering would probably be more useful for your example.
Include the MarkerClusterer script:
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
(or you can use a version from a different CDN)
Instantiate a MarkerClusterer:
// Add a marker clusterer to manage the markers.
new MarkerClusterer(map, markers, {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
proof of concept fiddle
(note: commented out the fitToMarkers call and set the zoom and center so it would show the cluster)
// Variables for Google maps
var map, mapElem, markerImg, infoWindow, marker;
var markers = [], infoWindows = [],
races = [{lat: 40.7127753, lng: -74.0059728, url:""},
{lat: 40.735657, lng:-74.1723667, url:""}];
var mapOptions = {
center: races[0], // add center to initialize map
zoom: 8, // zoom out so can see cluster
mapTypeId: 'roadmap',
//zoom: 13,
//scrollwheel: false,
styles: [
{
"featureType": "administrative",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#444444"
}
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"color": "#f2f2f2"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "all",
"stylers": [
{
"saturation": -100
},
{
"lightness": 45
}
]
},
{
"featureType": "road.highway",
"elementType": "all",
"stylers": [
{
"visibility": "simplified"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"color": "#2bb0e6"
},
{
"visibility": "on"
}
]
}
]
};
function initialize() {
markerImg = {
url:'https://uploads-ssl.webflow.com/5f58a4616a9e71d63ca059c8/5fa18680b95c219254ad0c9c_place-marker.png',
size: new google.maps.Size(46, 57),
anchor: new google.maps.Point(23, 54),
}
// Display a map on the page
mapElem = document.getElementById('map_canvas');
map = new google.maps.Map(mapElem, mapOptions);
map.setTilt(45);
// Loop through our array of races
for(i = 0; i < races.length; i++) {
var race = races[i];
// Generate an infowindow content for the marker
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(
'<div class="bg-race"</div>' +
'<p>'+race.name+'<br>Next race: '+race.date+'</p>' +
' Race wesbsite '
);
infoWindows.push(infoWindow);
// Place a marker on the map
createMarker(race.lat, race.lng, i);
}
// Add a marker clusterer to manage the markers.
new MarkerClusterer(map, markers, {
imagePath: 'https://unpkg.com/#google/markerclustererplus#4.0.1/images/m',
});
// Center the map fitting all markers on the screen
// fitToMarkers(); // comment out so can see clustering
}
function createMarker(x, y, i) {
marker = new google.maps.Marker({
map: map,
icon: markerImg,
position: new google.maps.LatLng(x,y),
title: races[i].name
});
marker._index = i;
markers.push(marker);
// Click event on marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// Close last opened infowindow if any
if(infoWindow) infoWindow.close();
// Open clicked infowindow
infoWindow = infoWindows[i];
infoWindow.open(map, marker);
}
})(marker, i));
}
function fitToMarkers() {
map.setZoom(13);
var bounds = new google.maps.LatLngBounds();
for(var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
map.setZoom(13); // zoom out when done so markers on the top can be seen
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map_canvas {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly"
defer
></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>

Get and draw GoogleMap Marker from JSON file

My simple application that get marker information from local JSON files and draws them.
It look like clear but I got a problem, it is just drawing the map, not show the marker.
I have consulted many guidelines and have applied but failed.
I sure added assets: - assets/data.json on pubspec.yaml
This is my main.dart code
class _MyHomePageState extends State<MyHomePage> {
Future _future;
List<Marker> allMarkers = [];
Future<String> loadJson() async =>
await rootBundle.loadString('assets/data.json');
GoogleMapController _controller;
#override
void initState() {
_future = loadJson();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: <Widget>[
FutureBuilder(
future: _future,
builder: (context, snapshot) {
if (snapshot.hasData) {
for (var v in snapshot.data) {
allMarkers.add(Marker(
markerId: v['id'],
position: LatLng(v['x'], v['y']),
));
}
return Text(snapshot.data);
} else {
return CircularProgressIndicator();
}
}),
GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(40.7128, -74.0060), zoom: 12.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
),
],
),
));
}
void mapCreated(controller) {
setState(() {
_controller = controller;
});
}
}
My data.json
[{
"rownum": 1,
"id": "E3E0D2C5-CB82-4AF3-8D5D-4CD323560F59",
"x": 40.7128,
"y": -74.0060,
}, {
"rownum": 2,
"id": "5FFB6736-7D1F-4B40-A397-32EB3128BC30",
"x": 41.7128,
"y": -71.0060,
}]

Style poi in flutter map_view

What is the equivalent of MapStyleOptions
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
in dart/flutter ?
How do style the map_view in flutter with the following style I got from https://mapstyle.withgoogle.com/
[
{
"featureType": "poi.government",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "poi.medical",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "poi.place_of_worship",
"stylers": [
{
"visibility": "off"
}
]
}
]
Here is my app:
import 'package:flutter/material.dart';
import 'package:map_view/map_view.dart';
var api_key = "AIzaSyDrHKl8IxB4cGXIoELXQOzzZwiH1xtsRf4";
void main() {
MapView.setApiKey(api_key);
runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
home: new MapPage(),
));
}
class MapPage extends StatefulWidget {
#override
_MapPageState createState() => new _MapPageState();
}
class _MapPageState extends State<MapPage> {
MapView mapView = new MapView();
CameraPosition cameraPosition;
var staticMapProvider = new StaticMapProvider(api_key);
Uri staticMapUri;
List<Marker> markers = <Marker>[
new Marker("1", "BSR Restuarant", 28.421364, 77.333804,
color: Colors.amber),
new Marker("2", "Flutter Institute", 28.418684, 77.340417,
color: Colors.purple),
];
showMap() {
mapView.show(new MapOptions(
mapViewType: MapViewType.normal,
initialCameraPosition:
new CameraPosition(new Location(28.420035, 77.337628), 15.0),
showUserLocation: true,
title: "Recent Location"));
mapView.setMarkers(markers);
mapView.zoomToFit(padding: 100);
mapView.onMapTapped.listen((_) {
setState(() {
mapView.setMarkers(markers);
mapView.zoomToFit(padding: 100);
});
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
cameraPosition =
new CameraPosition(new Location(28.420035, 77.337628), 2.0);
staticMapUri = staticMapProvider.getStaticUri(
new Location(28.420035, 77.337628), 12,
height: 400, width: 900, mapType: StaticMapViewType.roadmap);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Flutter Google maps"),
),
body: new Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Container(
height: 300.0,
child: new Stack(
children: <Widget>[
new Center(
child: Container(
child: new Text(
"Map should show here",
textAlign: TextAlign.center,
),
padding: const EdgeInsets.all(20.0),
),
),
new InkWell(
child: new Center(
child: new Image.network(staticMapUri.toString()),
),
onTap: showMap,
)
],
),
),
new Container(
padding: new EdgeInsets.only(top: 10.0),
child: new Text(
"Tap the map to interact",
style: new TextStyle(fontWeight: FontWeight.bold),
),
),
new Container(
padding: new EdgeInsets.only(top: 25.0),
child: new Text(
"Camera Position: \n\nLat: ${cameraPosition.center
.latitude}\n\nLng:${cameraPosition.center
.longitude}\n\nZoom: ${cameraPosition.zoom}"),
),
],
),
);
}
}
Looks like this (https://github.com/flutter/plugins/pull/1697) just got merged in yesterday. Still trying to figure it out but it is finally here!

Incorporating JSON from Google Maps API Wizard into existing html

I'm trying to customize the base map for a google fusion table. I'm using the Maps API Style Wizard and have created the map I want, but I'm at a loss as to how to incorporate the JSON code generated by the Map wizard into the html code for the existing page:
This is the map I'd like to customize: http://shatterbe.lt/ses_maps/per_capita_upper_eastside.html
And this is the code that the API Map wizard gave me:
[
{
"stylers": [
{ "visibility": "simplified" }
]
},{
"featureType": "road.highway",
"stylers": [
{ "visibility": "off" }
]
}
]
Someone help? I know the answer is probably very simple, but I'm new to all of this!
This works for me:
function initialize() {
var map = new google.maps.Map(document.getElementById('googft-mapCanvas'), {
center: new google.maps.LatLng(25.826923725271442, -80.18369569667362),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
styles: [
{
"stylers": [
{ "visibility": "simplified" }
]
},{
"featureType": "road.highway",
"stylers": [
{ "visibility": "off" }
]
}
],
heatmap: { enabled: false },
query: {
select: "col6",
from: "1_atSM8PGxxDThZlVGvFw4WlyaYHKuXU9CoCvGU0",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
Documentation describing how to add styling to the map
Example from the documentation