Blackberry: Passing KML file to Google Maps - google-maps

I want to know that can I pass KML as a string to google map application?
Code snippet:
//KML String
String document = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document><Folder><name>Paths</name><open>0</open><Placemark><LineString><tessellate>1</tessellate><coordinates> -112.0814237830345,36.10677870477137,0 -112.0870267752693,36.0905099328766,0</coordinates></LineString></Placemark></Folder></Document></kml>";
//Invoke Google Maps
int module = CodeModuleManager.getModuleHandle("GoogleMaps");
if (module == 0) {
try {
throw new ApplicationManagerException("GoogleMaps isn't installed");
} catch (ApplicationManagerException e) {
System.out.println(e.getMessage());
}
}
String[] args = {document}; //Is this possible???
ApplicationDescriptor descriptor = CodeModuleManager.getApplicationDescriptors(module)[0];
ApplicationDescriptor ad2 = new ApplicationDescriptor(descriptor, args);
try {
ApplicationManager.getApplicationManager().runApplication(ad2, true);
} catch (ApplicationManagerException e) {
System.out.println(e.getMessage());
}

After much R&D...the answer that I found out was that - No, we cannot pass KML as string.
Google Maps Mobile accepts a URL parameter. This needs to be in the form of "http://" and could be either specific parameters (such as "http://gmm/x?....") or a KML file ("http://..../sample.kml").

You MUST parse your mapFile (KML, gpx, txt) IF using the GoogleMaps API.
if all you want is to see your KML file inside a googlemaps window, you can goto the standard http://www.googlemaps.com and inside the ADDRESS box, you put the complete http address of your kml file.
until april2012 this used to work perfectly and the sidebar would be populated correctly, with clickable items (clicking on sidebar entry [e.g. "point 1" would fly-to the equivalent location). as of may2012, this feature is working incorrectly.
IF you want to take things one step further, you can have a PHP page echo the kml (on the fly KML rendering from database or file). BUT, googlemaps will not refresh your dynamically generated output for 10 to 15 minutes.
PM me if you want some javascript GPX and TXT mapFile rendering for GoogleMaps API vs3

Related

Can't import geojson value as string in google maps with firebase web

So, I set up my firebase to communicate with my web app which uses google maps api and my goal is this: When a user draws a shape on the map(polygon, linestring), I want to send the geoJson value of it to the firebase(currently sending it as a String), and then retrieve it back so it appears on the map for everyone(since it's getting synced from the firebase database). My problem is that when I try to retrieve the geoJson data back and add it on google maps, at the line map.data.addGeoJson(geoJsonString);(geoJsonString = geoJson value that is stored in firebase) I get an error saying:
Uncaught Jb {message: "not a Feature or FeatureCollection", name: "InvalidValueError", stack: "Error↵ at new Jb (https://maps.googleapis.com/m…tatic.com/firebasejs/4.13.0/firebase.js:1:278304)"}
For some reason google maps api doesnt accept the geoJson value even though console.log(geoJsonString); returns a valid geoJson value (checked at http://geojsonlint.com/)
Now the strange part is that if I try to import the same geoJson value manually(storing the geoJson value in a var and then map.data.addGeoJson(geoJsonString);) it works just fine.
This function syncs firebase with the web app
function gotData(data){
paths = data.val();
if(paths == null){
console.log("firebase null");
alert('Database is empty! Try adding some paths.');
}
else{
var keys = Object.keys(paths);
for(var i = 0; i < keys.length; i++){
var k = keys[i];
var geoJsonString = paths[k].geoJsonString;
console.log(geoJsonString);
map.data.addGeoJson(geoJsonString);
}
}
}
This function updates and pushes data in firebase
function updateData(){
data = {
geoJsonString: geoJsonOutput.value
}
ref = database.ref('firebasePaths');
ref.push(data);
}
In this function(which is used to store geoJson values locally in a file), I call updateData function), after a new path is drawn on the map
// Refresh different components from other components.
function refreshGeoJsonFromData() {
map.data.toGeoJson(function(geoJson) {
geoJsonOutput.value = JSON.stringify(geoJson);
updateData();
refreshDownloadLinkFromGeoJson();
});
}
Example of my firebase that contains 2 random geoJson
I can't trace where the problem is. Any ideas?
Update: I managed to fix this issue by parsing the string with JSON.parse("retrieved string from firebase"), saving it to a variable and then adding it to the map with map.data.addgeoJson(parsed variable).
We still have not faced that issue, however, we are aware of it.
Our intended solution is to use GeoFire: An open-source library for the Firebase Realtime Database that adds support for geospatial querying.
You can find the library description in here:
https://firebase.google.com/docs/libraries/
For the Web supported library:
https://github.com/firebase/geofire-js

Dart / flutter: download or read the contents of a Google Drive file

I have a public (anyone with the link can view) file on my Google Drive and I want to use the content of it in my Android app.
From what I could gather so far, I need the fileID, the OAuth token and the client ID - these I already got. But I can't figure out what is the exact methodology of authorising the app or fetching the file.
EDIT:
Simply reading it using file.readAsLines didn't work:
final file = new File(dogListTxt);
Future<List<String>> dogLinks = file.readAsLines();
return dogLinks;
The dogLinks variable isn't filled with any data, but I get no error messages.
The other method I tried was following this example but this is a web based application with explicit authorization request (and for some reason I was never able to import the dart:html library).
The best solution would be if it could be done seamlessly, as I would store the content in a List at the application launch, and re-read on manual refresh button press.
I found several old solutions here, but the methods described in those doesn't seem to work anymore (from 4-5 years ago).
Is there a good step-by-step tutorial about integrating the Drive API in a flutter application written in dart?
I had quite a bit of trouble with this, it seems much harder than it should be. Also this is for TXT files only. You need to use files.export() for other files.
First you need to get a list fo files.
ga.FileList textFileList = await drive.files.list(q: "'root' in parents");
Then you need to get those files based on ID (This is for TXT Files)
ga.Media response = await drive.files.get(filedId, downloadOptions: ga.DownloadOptions.FullMedia);
Next is the messy part, you need to convert your Media object stream into a File and then read the text from it. ( #Google, please make this easier.)
List<int> dataStore = [];
response.stream.listen((data) {
print("DataReceived: ${data.length}");
dataStore.insertAll(dataStore.length, data);
}, onDone: () async {
Directory tempDir = await getTemporaryDirectory(); //Get temp folder using Path Provider
String tempPath = tempDir.path; //Get path to that location
File file = File('$tempPath/test'); //Create a dummy file
await file.writeAsBytes(dataStore); //Write to that file from the datastore you created from the Media stream
String content = file.readAsStringSync(); // Read String from the file
print(content); //Finally you have your text
print("Task Done");
}, onError: (error) {
print("Some Error");
});
There currently is no good step-by-step tutorial, but using https://developers.google.com/drive/api/v3/manage-downloads as a reference guide for what methods to use in Dart/Flutter via https://pub.dev/packages/googleapis: to download or read the contents of a Google Drive file, you should be using googleapis/Drive v3, or specifically, the methods from the FilesResourceApi class.
drive.files.export(), if this is a Google document
/// Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
drive.files.get(), if this something else, a non-Gdoc file
/// Gets a file's metadata or content by ID.
Simplified example:
var drive = new DriveApi(http_client);
drive.files.get(fileId).then((file) {
// returns file
});
However, what I discovered was that this Dart-GoogleAPIs library seemed to be missing a method equivalent to executeMediaAndDownloadTo(outputStream). In the original Google Drive API v3, this method adds the alt=media URL parameter to the underlying HTTP request. Otherwise, you'll get the error, which is what I saw:
403, message: Export requires alt=media to download the exported
content.
And I wasn't able to find another way to insert that URL parameter into the current request (maybe someone else knows?). So as an alternative, you'll have to resort to implementing your own Dart API to do the same thing, as hinted by what this OP did over here https://github.com/dart-lang/googleapis/issues/78: CustomDriveApi
So you'll either:
do it through Dart with your own HttpClient implementation and try to closely follow the REST flow from Dart-GoogleAPIs, but remembering to include the alt=media
or implement and integrate your own native-Android/iOS code and use the original SDK's convenient executeMediaAndDownloadTo(outputStream)
(note, I didn't test googleapis/Drive v2, but a quick examination of the same methods looks like they are missing the same thing)
I wrote this function to get file content of a file using its file id. This is the simplest method I found to do it.
Future<String> _getFileContent(String fileId) async {
var response = await driveApi.files.get(fileId, downloadOptions: DownloadOptions.fullMedia);
if (response is! Media) throw Exception("invalid response");
return await utf8.decodeStream(response.stream);
}
Example usage:
// save file to app data folder with 150 "hello world"s
var content = utf8.encode("hello world" * 150);
driveApi.files
.create(File(name: fileName, parents: [appDataFolder]),
uploadMedia: Media(Stream.value(content), content.length))
.then((value) {
Log().i("finished uploading file ${value.id}");
var id = value.id;
if (id != null) {
// after successful upload, read the recently uploaded file content
_getFileContent(id).then((value) => Log().i("got content is $value"));
}
});

Upload a file to Google Drive with embedded browser c#

Since I am unable to capture browser window close event using the GoogleWebAuthorizationBroker.AuthorizeAsync API, I followed this link (http://www.daimto.com/google-api-and-oath2/) to create an embedded browser and authenticate the user. I am unable to continue further to use the access token to upload a file in google drive. Is there any example available to continue from the above link to upload/download a file from Google Drive.
Regards,
Amrut
From the same author, there is a documentation how to upload/ download files to Google Drive.
Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console. Under APIs be sure to enable the Google Drive API and Google Drive SDK, as always don’t forget to add a product name and email address on the consent screen form.
Make sure your project is at least set to .net 4.0.
Add the following NuGet Package
PM> Install-Package Google.Apis.Drive.v2
In order to download a file we need to know its file resorce the only way to get the file id is from the Files.List() command we used earlier.
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
{
if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
try
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
byte[] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo, arrBytes);
return true;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return false;
}
}
else
{
// The file doesn't have any content stored on Drive.
return false;
}
}
Using _service.HttpClient.GetByteArrayAsync we can pass it the download url of the file we would like to download. Once the file is download its a simple matter of wright the file to the disk.
Remember from creating a directory in order to upload a file you have to be able to tell Google what its mime-type is. I have a little method here that try’s to figure that out. Just send it the file name. Note: When uploading a file to Google Drive if the name of the file is the same name as a file that is already there. Google Drive just uploads it anyway, the file that was there is not updated you just end up with two files with the same name. It only checks based on the fileId not based upon the file name. If you want to Update a file you need to use the Update command we will check that later.
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}

Serving urls to a Web view controller in Java javafx

I'm trying to serve requests to Google API using a JavaFX app. I'm using the Google roads API. Problem is I'm asking user to import an excel document with coordinates and the document can hold as many latitude and longitude data as possible but the Google API only allows less than 100 pairs of coordinates. So how can I serve the data which is in an array list from index at position 0 to 99 and on button press serve the next set of coordinates from 100 to 199 or less. I'm currently able to serve the arraylist.sublist(0to99) and get back a json response. Thanks in advance
//On fx button click the following happens
#FXML public void loadURL(Event event){
co_ordinates = Excel_Exchange.value;
if(!next){
limit = (int)co_ordinates.size();
next = true;//some global boolean variable so that this is done once
}
if(co_ordinates.size()<100){
StringBuilder urlCaseOne = new StringBuilder(co_ordinates.subList(start, co_ordinates.size()).toString().replaceAll("[\\[\\]]","").replaceAll(", ",""));
url_link = "https://roads.googleapis.com/v1/snapToRoads?path="+urlCaseOne.deleteCharAt(urlCaseOne.length()-1)+"&interpolate=true&key="+API_KEY;
}else{
if(limit>100){
StringBuilder urlCaseTwo = new StringBuilder(co_ordinates.subList(start, end).toString().replaceAll("[\\[\\]]","").replaceAll(", ",""));
url_link = "https://roads.googleapis.com/v1/snapToRoads?path="+urlCaseTwo.deleteCharAt(urlCaseTwo.length()-1)+"&interpolate=true&key="+API_KEY;
//System.out.println("l"+limit+" s"+start+" e"+end);
start+=100; end+=100; limit-=100;
}else if(limit<100){
StringBuilder urlCaseThree = new StringBuilder(co_ordinates.subList(start, co_ordinates.size()).toString().replaceAll("[\\[\\]]","").replaceAll(", ",""));
url_link = "https://roads.googleapis.com/v1/snapToRoads?path="+urlCaseThree.deleteCharAt(urlCaseThree.length()-1)+"&interpolate=true&key="+API_KEY;
}
}
//System.out.println(co_ordinates.size());
//System.out.println(url_link);
//System.out.println(co_ordinates.toString().lastIndexOf("|"));
//System.out.println(co_ordinates.subList(0, 99).size());
startLoadState.apply();
this.engine.load(url_link);
}// i have another method that navigates back by to the first url

Problem to pass a kml file to Google Earth using geoxml3 class and ProjectedOverlay class

i am trying to build a google earth view showing cities, but i stuck with the kml parser geoxml3. I have a javascript building a google map at first showing the locations i want. this works fine. I call the function from a php script providing it an address and kml file reference from database. The function builds the map, sets a flag 'map_finished' as a control flag when all ran fine and calls the build google earth view function.
// Get maps and earth from google
google.load( 'maps', '2.s', {'other_params': 'sensor=true'} );
google.load( 'earth', '1' );
//Google Earth Initializer
function initObjectEarth() {
// Check if Google Earth plugin is installed
if( gm_loaded ) {
this.ge_plugin_installed = google.earth.isInstalled();
if( this.ge_plugin_installed ) {
google.earth.createInstance( 'inmap', geSuccessCallback, geFailureCallback );
ge_loaded = true;
} else {
alert( 'Your Browser has not yet installed the Google Earth plugin.
We recommend installing it to use all features!' );
return false;
}
}
}
// Success handler
function geSuccessCallback( object ) {
this.ge = object;
this.ge.getWindow().setVisibility( true );
this.kmlParser = new geoXML3.parser();
}
// Error handler
function geFailureCallback( object ) {
alert( 'Error: ' + object );
}
The geoxml parser uses the ProjectedOverlay class. Both libraries are loaded into document head. When the parser is getting instatiated it requests a ProjectedOverlay instance. This class throws a
Error: **google.maps is undefined**
error in firebug for the following statement
ProjectedOverlay.prototype = new google.maps.OverlayView();
In my script file i have declared vars including
var gm //for google map
var ge //for google earth
gm is set in the function that builds the google map.
I wonder how to fix this issue. I tried the getProjection() thing i found in web as well as
ProjectedOverlay.prototype = new google.maps.OverlayView().prototype;
with no success. This topic is absolutely new to me and i cannot figure out how to fix it neither from the documentation of OverlayView nor from google search.
What did i forget or do wrong?
The call to the geoXML3 constructor is wrong, you must pass the google.maps object as a parameter (...hence the "google.maps is undefined" error).
this.kmlParser = new geoXML3.parser({map: gm}); // gm for google map