I just start to learn more about dart and flutter and followed some tutorials. Now I have a start with a Google maps app and what i want to do is to import my own polylines.
Normally the polylines are generated automatically between the start and destination point but i want to change that:
This is the automatic standard:
List<LatLng> polylineCoordinates = [];
This is how I can manually change that.
List<LatLng> polylineCoordinates = [
LatLng (4.6546609, 52.2997741),
LatLng (4.6539206, 52.2998594),
LatLng (4.6522898, 52.3002268),
LatLng (4.651689, 52.3002793),
];
Now I dont want to manually add it in the code but I want to fill it from a file(json, csv)
What is best to do and how can I start.. Hope someone can help me.
Your question is more like "how to read data from json/csv into dart code".
Anyway, here's a standard way to do it:
Assuming that you have the values in a json file like the following:
{
[
{ 'lat':33.22222,
'long':20.25451
},
{ 'lat':30.89222,
'long':20.55551
}
]
}
Declare the json file in the pubspec.yaml
flutter:
assets:
- assets/sample.json
Write a function that parses the json
readJson() async {
final String assetFile = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(assetFile);
return data;
}
Use that data for your desired logic
List<LatLng> polylineCoordinates = readJson().map((e)=>LatLng(e['lat'], e['long']).toList;
Related
I'm working in Angular trying to display some image data I'm getting from an external api. I've tried a few things like converting this data to a Blob to display an image but I'm not having any luck. This is what the data looks like:
����JFIF��C\t\t\t\n\n\n\n\n\n\t\n\n\n��+��\t\n���}!1AQa"q2���#B��R��$3br�\t\n%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������?��=��[��4�\r�j���U�t{��|���#&#w��Z�����R.��.��\r>�b��;2\��1#��>��KY�d�����#�;��k��Y\r���8e8S��u��JZ4�p���ֺ?�����19�dkr�j\r��ְ��"��.\to\b�ܗ��m��%�3�iI���j…��?�C�&k��d�=�����}҅#���5j�9m�+�����\Lm�9��~��lU#,W'i��Gn�D ��:b�����Lv�'����.ck�c��<�w�$�!U��#��f��_%�8�f]j�(��2��\n�F�suu br?�Mew4��3��r=s�r��cs�#�ޑ�{ˋ���9<qP��|��I�OmZh7Z����泯�)��d�GR~��{}s<g�����+�Z)���'֦�Q�;�_���jr��ӧ!'��[S�/r�X���yI-�ЎO���ז��h�,����=��\n�?��b4{�aP�fx�����?ah�-�e�s�p7q����^c�,I#�����B��}��\\��_V�z���"i����ZcS�BT �s���}vK(ZY���>�^��o��zZ�m�a��qU�P��rO=�"�'Y�?���V�i��;��Sǵs����v����sI</�9'=sU�[X)݃��kv��\\d7j�ӡ�v�T���
Another piece of information that could be helpful is when I call the api from Postman, it displays the image correctly in the response body.
Any help is appreciated.
Thanks.
Edit:
Currently what I am doing is converting this jpeg data to a buffer, creating a blob from the buffer, using that blob to create an object url and assigning that object url to the image src. All this does is return the unable to load image icon.
const buffer = Buffer.from(image.data);
const blob = new Blob(buffer.data, { type: 'image/jpeg' });
const image = URL.createObjectURL(blob);
const imageTag = document.getElementById('fullImage');
(imageTag as HTMLImageElement).src = image;
Your blob doesn't seem to be valid base64.
In template you could do:
<img [src]="myImage">
Import DomSanitizer, define it in the constructor and then sanitize Base64 string you want to pass as your image source (use trustResourceUrl):
import { DomSanitizer } from '#angular/platform-browser';
constructor(private sanitizer: DomSanitizer) { }
base64string: string; // your blob here
myImage: string; // image string to template
blobToImage() {
this.myImage = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,'
+ base64string);
}
Angular http client converts requests to json unless you explicitly tell it not to. This could be why the image data you're getting isn't what you're expecting.
Try setting { responseType: 'blob' } in the get request options.
Thanks to the input from Mike and Joosep.P I learned that my image data was getting corrupted as it was passed back from my api. I decided to forgo calling the external api from my api and just did it from my front-end instead. Once I did that converting the blob data was easy.
this.imagingSerivce.getImage(imageId, response.server, response.token).subscribe((response2: any) => {
const imageTag = document.getElementById('fullImage');
const reader = new FileReader();
reader.readAsDataURL(response2);
reader.onloadend = () => {
(imageTag as HTMLImageElement).src = '' + reader.result;
};
});
I want get json file on ftp server and convert this in map to use the objects.
I can do this.
Map myMap = new Map();
http
.get('link.com')
.then((response) =>{
myMap = json.decode(Utf8Decoder().convert(response.bodyBytes))})
.whenComplete(() => {
myMap.forEach((key, value) {
setState(() {
print(value);
});
})
});
But I want to write the map to a file in my application folder and read the locally stored file.
but when I'm trying with my model file I can't because I have
{name: [{title: title, content: content}]}
and not
"name": [{"title": "title","content":"content"}]}
So I can't create a Map from the string.
How can I solve this?
Instead of saving the file using myMap.toString() use json.encode to encode the map to a valid json string and save that that way you can decode it again when reading the file.
How can I use JSON.stringify with a Typescript Map. The presumption is the Map keys are all strings.
In this example, the console output is an empty {}
const myMap = new Map<string, Employee>();
myMap.set('employee1', new Employee());
myMap.set('employee2', new Employee());
myMap.set('employee3', new Employee());
console.log('myMap', JSON.stringify(myMap));
this way you can stringify the Map value
JSON.stringify([...myMap])
and if you want to convert the value back to Map
let obj = JSON.parse(stringifyValue)
let myMap = new Map();
for (let k of Object.keys(obj)) {
myMap.set(k, obj[k]);
}
check this Converting ES6 Maps to and from JSON
I've been in the process of migrating a code base from Angular 4.x to 5.x, and I'm running into a strange issue. I have a service function, that is intended to return a list of objects to the front end, which I then massage into a specific data format. I know I'll need to keep the mapping, but I'm a little miffed that it's returning just plain string data.
The original function is this: (using Http from #angular/http just renamed to HttpClient)
public GetVendors(showAll = true, screenArea: number = 0): Observable<Array<SelectModel>> {
let link = AppSettings.API_COMMON_VENDORS;
let params: URLSearchParams = new URLSearchParams();
params.set('showAll', showAll.toString());
params.set('screenArea', screenArea.toString());
let requestOptions = new RequestOptions();
requestOptions.search = params;
return this.httpClient.get(link, requestOptions).map(response => {
let result = JSON.parse(response.json());
let list = new Array<SelectModel>();
let vendors: Array<any> = result;
vendors.forEach(vendor => {
list.push(this.CreateSelectModel(vendor));
});
return list;
});
}
and after ripping out ALL of the Http code, here's the function again using HttpClient from #angular/common/http
public GetVendors(showAll = true, screenArea: number = 0): Observable<Array<SelectModel>> {
let link = AppSettings.API_COMMON_VENDORS;
let params: HttpParams = new HttpParams()
.set('showAll', showAll.toString())
.set('screenArea', screenArea.toString());
return this.httpClient.get<Array<any>>(link, {params}).map(response => {
let list = new Array<SelectModel>();
response.forEach(vendor => {
list.push(this.CreateSelectModel(vendor));
});
return list;
});
}
The issue with this is it kind of defeats the purpose of the new client parsing json for me. The response object is a string representing the JSON of the data I requested, but it's still in a string form, and not the type defined in the get<>() call.
What am I doing wrong here? shouldn't it be parsed already?
Sample Response Data A'la Network Tools in Chrome Dev Tools:
Sample Response Body:
Dev Tools Screenshot with Value of response
The backend (C#) responds with this:
[HttpGet]
public JsonResult Vendors(bool showAll = false, int screenArea = 0)
{
var vendors = _commonBL.GetVendorsSlimForUser(UserModel, UserModel.CustomerId, showAll, screenArea);
return GetJson(vendors);
}
this is how it worked before the Http => HttpClient migration, and it worked with ONE JSON.parse() The data in the return line is simply a standard List<T>
This is what the raw response for your data should look like:
[{"Id":1234,"Name":"Chris Rutherford"}]
But this is what it actually looks like:
"[{\"Id\":1234,\"Name\":\"Chris Rutherford\"}]"
So somewhere in your server code, you have applied JSON encoding twice. Once you correct that, HttpClient will do the right thing.
I'd quote an answer from this thread. Hope it will shed some light on how things work, read it thoroughly it enlightened me tough its not easy to find.
TypeScript only verifies the object interface at compile time. Any object that the code fetches at runtime cannot be verified by
TypeScript.
If this is the case, then things like HttpClient.Get should not
return Observable of type T. It should return Observable of type Object because
that's what is actually returned. Trying to state that it returns T
when it returns Object is misleading.
In the documentation the client's return section says this:
#return an Observable of the body as
type T.
In reality, the documentation should say:
#return an Observable of the body which
might be T. You do not get T back. If you got T back, it would
actually be T, but it's not.
I really need to find some information inside a JSON file, in Java I can easily find a string from a JSON Object with
JSON_Object.getString("String Here");
But I cannot find anything similar in Dart. So far all I can see is:
var jsonobject = new JsonObject.fromJsonString(jsonString);
print(jsonobject.something);
but the problem with this is that I cannot find a String nested in other bits of JSON. Here is the JSON I am using:
http://maps.google.com/maps/api/geocode/json?latlng=51.4346502,-0.1020349
Thanks,
Luca
this is some code that does the trick. You might have to change it a little bit to fit your needs:
import 'package:http/http.dart';
import 'dart:convert';
void main() {
get('http://maps.google.com/maps/api/geocode/json?latlng=51.4346502,-0.1020349').then((Response response) {
var json = JSON.decode(response.body);
json['results'].forEach((result){
print(result['formatted_address']);
});
});
}
If you know the structure of your JSON you can access it directly
var json = ...
print(json["results"][0]["formatted_address"]);