Im implementing a flutter app to display polylines by flutter google maps plugin, But It only shows a straight line between those two points rather than showing actual route, I'm not quite sure what needed to do.
Here my add markers function
void addMarker() {
latlng.add(LatLng(5.973804, 80.429838));
allMarkers.add(Marker(
markerId: MarkerId('busLoc'),
draggable: true,
onTap: () {
print('Marker Tapped');
},
position: LatLng(5.973804, 80.429838),
));
_polyline.add(Polyline(
color: Colors.blue,
visible: true,
points: latlng,
polylineId: PolylineId("distance"),
));
Here my scaffold
GoogleMap(
polylines: _polyline,
markers: Set.from(allMarkers),
initialCameraPosition:
CameraPosition(target: LatLng(widget.la, widget.l0), zoom: 14),
mapType: MapType.normal,
),
And I'll attach screenshot below as well
To get the route from point A to point B you will need to use Directions API that is available on the google_maps_webservice flutter package, which is a service from Google Maps Platform that gives the route information
One of the route information is the overview_polyline that holds an encoded polyline representation of the route.
You can get the overview_polyline by having a function that sends request to Directions API using the google_maps_webservice package like this:
import 'package:google_maps_webservice/directions.dart' as directions;
final _directions = new directions.GoogleMapsDirections(apiKey: "YOUR_API_KEY");
var overviewPolylines;
directions.DirectionsResponse dResponse = await _directions.directionsWithAddress(
_originAddress,
_destinationAddress,
);
if (dResponse.isOkay) {
for (var r in dResponse.routes) {
overviewPolylines = r.overviewPolyline.points
}
}
Then, once you get the overview_polyline from Directions API using the sample code above, you will need to decode it using the PolyUtil(); method from the google_maps_util flutter package like this:
import 'package:google_maps_util/google_maps_util.dart';
PolyUtil myPoints = PolyUtil();
var pointArray = myPoints.decode(overviewPolylines);
Once decoded you can pass the pointArray to your polyline object like this:
_polyline.add(Polyline(
color: Colors.blue,
visible: true,
points: pointArray,
polylineId: PolylineId("distance"),
));
it shows straight line because you have in your polyline only two points, so the expected behavior is to draw a line from one point to the other
you have to use google direction API here is an article explains how to draw route between two points in flutter.
https://medium.com/flutter-community/drawing-route-lines-on-google-maps-between-two-locations-in-flutter-4d351733ccbe
Related
On map using cluster layer to display the marker , on API call loading the data on reload i need to clear clustered marker in the map please help on this issue,normal marker to clear using current method (map.removeObjects(map.getObjects()) it working as excepted but i need remove default cluster marker
Please find the below code :
startClustering(map, data) {
// First we need to create an array of DataPoint objects,
// for the ClusterProvider
// tslint:disable-next-line:ter-prefer-arrow-callback
const dataPoints = data.map(function (item) {
console.log('item>>>>', item);
return new H.clustering.DataPoint(item.y, item.x);
});
const clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
// Maximum radius of the neighbourhood
eps: 1,
// minimum weight of points required to form a cluster
minWeight: 2,
},
});
// Create a layer tha will consume objects from our clustering provider
const clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
// To make objects from clustering provder visible,
// we need to add our layer to the map
map.addLayer(clusteringLayer);
}
i need to remove this cluster marker before call this funcation
The easiest approach will be to keep a reference to the cluster layer you wish to remove and then remove it by:
Given a reference called clusteringLayer:
map.removeLayer(clusteringLayer);
The other alternative of using map.getLayers() to retrieve all map layers and removing each layer via map.removerLayer(<layerRef>) might remove layers you do not wish to remove.
I want ask you to one thing about interactive map and geo service. I need to get altitude from my coordinations points and build graph of elevation.
In google maps it looks like this:
https://developers.google.com/maps/documentation/javascript/examples/elevation-paths
I didn't found any example for this. How can I solve this problematic?
Thank you very much.
Best regards Petr Tomasek
You can build a similar elevation graph via the HERE RoutingService JS API by specifying the value of returnelevation of the routeRequestParams to true like in this snippet:
var router = platform.getRoutingService();
var routeRequestParams = {
mode: 'fastest;car',
representation: 'display',
waypoint0: '{lat, lng}', // Start of route
waypoint1: '{lat, lng}', // End of route
returnelevation: true
};
var onResult = function(result) {
var route = result.response.route[0];
/* Now, altitudes are the third values of the each shape point.
Note: Shape points returned as strings. */
var elevation_list = route.shape.map(x => parseFloat(x.split(",")[2]));
/* Now you can use the elevation_list as input data to
draw your elevation graph with any graph tool
*/
};
var onError = function(error) {
console.log(error);
};
router.calculateRoute(
routeRequestParams,
onResult,
onError
);
With the elevation values you can draw your elevation graph with any JS graph library.
Checkout the routing API: https://developer.here.com/documentation/maps/topics/routing.html
I'm new to javascript and I'm working on a project which needs to google maps.
I need to use the text search function to find nearby veterinary request a postcode does not work and I have several questions.
Do I need an API key to use the service places?
I Copied the code documentation google maps but don't understand the callback function and i don't know if something I'm doing is wrong.
If anyone has any idea what's wrong with the code, I would greatly appreciate your response.
This is my code:
<script src="https://maps.googleapis.com/maps/api/js?callback=ini&sensor=false&libraries=places"></script>
<script type="text/javascript">
var map;
var vet= " veterinarys";
ini();
function ini()
{
var mapOptions =
{
center: new google.maps.LatLng(37.7831, -122.4039 ),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var request =
{
radius: '500',
query: vet,
type: ['veterinary_care']
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
</script>
API key is optional, but you have to pay attention to this note.
The Google Maps JavaScript API does not require an API key to function correctly. However, we strongly encourage you to load the Maps API using an APIs Console key which allows you to monitor your application's Maps API usage.
Callback parameter in the script URL is required if you load resource asynchronously. In that case as soon as Google Maps script will be loaded it will call your function. In your case to start use it you should add async attribute to the <script> tag and remove direct ini() function call from the code. Here you find documented explanation for callback param
Your code doesn't work because you specify radius param which requires location to be specified as well. It should work if you will add the same location to the request object as center param in mapOptions. Just check available options description.
You got the rest of the help from #Mihails Boturins's answer. I will answer for the question you asked in your last comment.
There is no such createMarker function defined in you code. You have to create that function just like this
i successfully created the linechart how many people visited my site from different countries. here is my code:
var API_KEY = 'MY_API_KEY';
var CLIENT_ID = 'CLIENT_ID';
var TABLE_ID = 'ga:XXX';
gadash.configKeys({
'apiKey': API_KEY,
'clientId': CLIENT_ID
});
var chart1 = new gadash.Chart({
'type': 'LineChart',
'divContainer': 'country_visitors',
'last-n-days':30,
'query': {
'ids': TABLE_ID,
'metrics': 'ga:visits',
'dimensions': 'ga:country'
},
'chartOptions': {
height:600,
title: 'Visitors from countries (Last 30 days)',
hAxis: {title:'Date'},
vAxis: {title:'Visits'},
curveType: 'function'
}
}).render();
but what i need is to show the data in geomap instead of linechart like it shows in dashboard when you log in google analytics account. i tried to change the type to GeoMap but it shows only the table not geo map. i also read the documentation on Visualization: Geomap. what i saw there is i need to give the data in an array and i don't have any idea how to do that. can anyone please help me with what i need? and one more thing when i was generating the line chart it asked me to authorize analytics, what should i do to view the analytics data without logging in. i would really appreciate your help.
I am using DirectionRenderer(gmap3) to show the user directions. The problem is it shows a match even if it cannot find an exact match. Eg: SomeFakePlace, myRealCity will match myRealCity even if it cannot match SomeFakePlace.
So it shows the directions from City's center to the place, instead. The destination is fixed(myLatLng)
I want it to return null and not show a route if cannot find one. I have decent error display to handle that.
$("#map-canvas-single").gmap3({
getroute:{
options:{
origin:$("#directions-from").val(),
destination:myLatlng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function(results){
console.log(results);
var point= results.routes[0].overview_path[0]
window.directionMarker = new google.maps.Marker({
position: new google.maps.LatLng(point.jb,point.kb),
title:$("#directions-from").val(),
//icon:"http://maps.google.com/mapfiles/ms/icons/<?php if($this->listing->type=="pg"):?>green<?php else: ?>purple<?php endif;?>-dot.png"
});
window.directionMarker.setMap($(this).gmap3("get"));
if(!results)
noty({text:"Place not found!",type:"error"});
else
{
$(this).gmap3({
directionsrenderer:{
container: $("#directions-container"),
id:"directions",
options:{
directions:results,
suppressMarkers :true //<<Look here>>
}
}
});
}
}
}
});
The code works fine and all. I think this the fault of direction renderer service, not gmaps. I am sure htere must be some parameter for an exact match
I'm not familiar with Google Maps API, but what I'd do is do a geocode lookup on the source address and find the lat, lng. You'll usually get coordinates with levels of confidence, so you can have a minimum threshold below which to throw an error.
https://developers.google.com/maps/documentation/geocoding/
Also, don't forget mapquest.
http://developer.mapquest.com/web/products/dev-services/geocoding-ws