AndroidStudio/GoogleMapv2: Array of LatLng/Multiple Latlng To Make A Route - json

I know routing is an old topic but all tutorials for Multiple LatLng to a Route following the roads are not working anymore, due from obsolete package of V1 and the new V3 I don't know where to start to code a Jeepney Route anymore. Im having this problem for a week now and my thesis is coming.
Anybody could help me explain further about this code from Neonigma?
private ArrayList<LatLng> getPolylines(String jsonStr) {
// file exists, it is the first boot
if (jsonStr != null) {
// linea init
LatLng polyline;
// array list of lines init
ArrayList<LatLng> polylines = new ArrayList<LatLng>();
// get json array
JSONArray jsonArray = JSON.getJSONArray(jsonStr, "polytag");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPolyline;
try {
jsonPolyline = jsonArray.getJSONObject(i);
polyline = new LatLng(Double.valueOf(jsonPolyline.getString("lat")),
Double.valueOf(jsonPolyline.getString("lon")));
polylines.add(polyline);
} catch (JSONException e) {
Log.d(TAG, "JSONException reading polylines: " + e.getMessage());
} catch (Exception e) {
Log.d(TAG, "Exception reading polylines: " + e.getMessage());
}
}
return polylines;
}
return null;
}
The code seems to run for an array of LatLng but I don't know how to fill the missing codes. I am aiming to build multiple coordinates to become a road map through Google Maps. Can anybody help me?

Related

How do I read json data (Latitude, Longitude) and convert it to polyline (Kotlin)

I have a list of lat,long data in json format (AIRPORTS.jsin), I want to read it and convert it to polylines. After writing a function to do that, It does not show in the mapActivity
This is what I have done
fun getPolylines(fileName: String?):
MutableList<LatLng>? {
var polyline: LatLng
// array list of lines init
val polylines = mutableListOf<LatLng>()
val inputStream = fileName?.let {
application.assets.open(it).bufferedReader()
}
var Json_string = inputStream.use {
it?.readText() ?: null
}
// get json array
val jsonArray = JSONArray(Json_string)
for (i in 0 until jsonArray.length()) {
var jsonPolyline: JSONObject
try {
jsonPolyline = jsonArray.getJSONObject(i)
polyline = LatLng(
(jsonPolyline.getDouble("lat")),
(jsonPolyline.getDouble("lon"))
)
polylines.add(polyline)
} catch (e: JSONException) {
Log.d(ContentValues.TAG, "JSONException reading polylines: " + e.message)
} catch (e: Exception) {
Log.d(ContentValues.TAG, "Exception reading polylines: " + e.message)
}
}
return polylines
}
I then called it in onMapListener
//add polylines
var polylines: MutableList<LatLng>? = getPolylines("IPO_OMAGWA.json")
map.addPolyline(PolylineOptions()
.addAll(polylines!!)
.pattern(Arrays.asList(Dot(), Gap(10.0f)))
.geodesic(true)
.zIndex(5F)
)
but its not showing

Using both CSVListReader and CSVBeanreader in superCSV

I want to read different CSV files which have all a fixed column number but 2 different files have 2 different column numbers. All the files have a headerline.
So I first use a CSVListReader to get the header and the column numbers and then construct the cell processors and the a CSV BeanReader to map the actual lines to POJO.
I tried first to make it work with passing InputStreamReaders to the superCsv readers constructors and it doesn't work. Works fine however with FileReaders or BufferedReaders.
Is it a bug or it just does not make sense to use InputStremReaders in this situation?
Here is the working code example
CsvListReader listReader = null;
FileReader file = null;
BufferedReader b = null;
try {
file = new FileReader(linkToFile);
b = new BufferedReader(file);
listReader = new CsvListReader(b,
CsvPreference.STANDARD_PREFERENCE);
csvHeader = listReader.getHeader(true);
} catch (IOException e) {
logger.info("Did not manage to get the Csv Header", e);
try {
listReader.close();
file.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
return;
}
}
try {
file = new FileReader(linkToFile);
b = new BufferedReader(file);
beanReader = new CsvBeanReader(b,
CsvPreference.STANDARD_PREFERENCE);
beanReader.getHeader(false);
extractCSV(beanReader, csvHeader);
catch (IOException e) {
logger.info("Did not manage to get a working CsvBeanReader.", e);
try {
beanReader.close();
listReader.close();
file.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
}
return;
}
Thanks in advance
As per Hound Doc Comments, the reason of the mess up was in a bad management of closing the different readers.
Below is the working code using input stream readers
// Reading the Header. A CsvListReader object is used here as it can
// read a variable number of columns in the first line (see
// http://supercsv.sourceforge.net/readers.html)
CsvListReader listReader = null;
InputStreamReader b = null;
try {
b = new InputStreamReader(new BufferedInputStream(new FileInputStream(linkToFile)));
listReader = new CsvListReader(b, CsvPreference.STANDARD_PREFERENCE);
csvHeader = listReader.getHeader(true);
} catch (IOException e) {
logger.info("Did not manage to get the Csv Header", e);
} finally {
try {
listReader.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
return;
}
}
// Using the CSV bean reader to read the file. Now we know the number of
// columns
// A CsvBeanReader object is the choice to extract easier to POJO
// structure
CsvBeanReader beanReader = null;
try {
b = new InputStreamReader(new BufferedInputStream(new FileInputStream(linkToFile)));
beanReader = new CsvBeanReader(b, CsvPreference.STANDARD_PREFERENCE);
// beanReader starts reading from line 2 (see above)
// it is as if we would be reading a file without a header
beanReader.getHeader(false);
extractCSVContacts(beanReader, csvHeader);
} catch (IOException e) {
logger.info("Did not manage to get a working CsvBeanReader.", e);
return;
}
finally {
try {
beanReader.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
}
}

No results in Australia using Bing Maps SOAP

I'm creating an app for WP8 and i've been using the Bing Maps tutorial. However I don't get any results in Australia. Do I need to use a completely different API? geolocale contains a string such as "20.002, -150.2222" even if I change it to just "California" it gets results. What am I doing wrong?
I've tried to find answers in a lot of places but can't seem to find anything that's relevant.
try
{
searchService.SearchCompleted += new EventHandler<SearchService.SearchCompletedEventArgs>(MySearchCompleted);
SearchService.SearchRequest mySearchRequest = new SearchService.SearchRequest();
mySearchRequest.Credentials = new SearchService.Credentials();
mySearchRequest.Credentials.ApplicationId = "key";
SearchService.StructuredSearchQuery ssQuery = new SearchService.StructuredSearchQuery();
ssQuery.Keyword = "coffee";
ssQuery.Location = geolocale;
mySearchRequest.StructuredQuery = ssQuery;
searchService.SearchAsync(mySearchRequest);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Coordinate 20.002, -150.2222 is in the middle of the Pacific ocean. Also, the Bing Maps SOAP services are an old legacy API. The Bing Spatial Data Services should be used.
http://msdn.microsoft.com/en-us/library/ff701734.aspx
http://rbrundritt.wordpress.com/2012/01/17/dynamically-updating-data-in-bing-maps-v7/
To use the Bing Spatial Data Services in WP8 first copy the Response, ResultSet, and Result classes from this project: http://code.msdn.microsoft.com/Augmented-Reality-with-bcb17045/sourcecode?fileId=85735&pathId=1819751232
You can then use the following code to generate your search query.
string baseURL;
//Switch between the NAVTEQ POI data sets for NA and EU based on where the user is.
if (Longitude < -30)
{
//Use the NAVTEQ NA data source: http://msdn.microsoft.com/en-us/library/hh478192.aspx
baseURL = "http://spatial.virtualearth.net/REST/v1/data/f22876ec257b474b82fe2ffcb8393150/NavteqNA/NavteqPOIs";
}
else
{
//Use the NAVTEQ EU data source: http://msdn.microsoft.com/en-us/library/hh478193.aspx
baseURL = "http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs";
}
//Search radius should be converted from meters to KM.
string poiRequest = string.Format("{0}?spatialFilter=nearby({1:N5},{2:N5},{3:N2})&$format=json&$top={4}&key={5}",
baseURL, Latitude, Longitude, SearchRadius / 1000, MaxResultsPerQuery, BingMapsKey);
You will need a method to pass this query to and serialize the results. Use the following:
private void GetResponse(Uri uri, Action<Response> callback)
{
System.Net.WebClient client = new System.Net.WebClient();
client.OpenReadCompleted += (s, a) =>
{
try
{
using (var stream = a.Result)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
if (callback != null)
{
callback(ser.ReadObject(stream) as Response);
}
}
}
catch (Exception e)
{
if (callback != null)
{
callback(null);
}
}
};
client.OpenReadAsync(uri);
}
Finally you will need to call the GetResponse method to make your query like this:
GetResponse(new Uri(poiRequest), (response) =>
{
if (response != null &&
response.ResultSet != null &&
response.ResultSet.Results != null &&
response.ResultSet.Results.Length > 0)
{
//Do something with the results
}
});

net.rim.device.api.io.file.FileIOException: File system out of resources in blackberry

Below code throws net.rim.device.api.io.file.FileIOException: File system out of resources this exception.
Can anyone tell me how it happens?
public Bitmap loadIconFromSDcard(int index) {
FileConnection fcon = null;
Bitmap icon = null;
InputStream is=null;
try {
fcon = (FileConnection) Connector.open(Shikshapatri.filepath + "i"
+ index + ".jpg", Connector.READ);
if (fcon.exists()) {
byte[] content = new byte[(int) fcon.fileSize()];
int readOffset = 0;
int readBytes = 0;
int bytesToRead = content.length - readOffset;
is = fcon.openInputStream();
while (bytesToRead > 0) {
readBytes = is.read(content, readOffset, bytesToRead);
if (readBytes < 0) {
break;
}
readOffset += readBytes;
bytesToRead -= readBytes;
}
EncodedImage image = EncodedImage.createEncodedImage(content,
0, content.length);
image = resizeImage(image, 360, 450);
icon = image.getBitmap();
}
} catch (Exception e) {
System.out.println("Error:" + e.toString());
} finally {
// Close the connections
try {
if (fcon != null)
fcon.close();
} catch (Exception e) {
}
try {
if (is != null)
is.close();
is = null;
} catch (Exception e) {
}
}
return icon;
}
Thanks in advance...
Check this BB dev forum post - http://supportforums.blackberry.com/t5/Java-Development/File-System-Out-of-Resources/m-p/105597#M11927
Basically you should guaranteedly close all connections/streams as soon as you don't need them, because there is a limited number of connection (be it a file connection or http connection) handles in OS. If you execute several loadIconFromSDcard() calls at the same time (from different threads) consider redesign the code to call them sequentially.
UPDATE:
To avoid errors while reading the content just use the following:
byte[] content = IOUtilities.streamToBytes(is);
And since you don't need file connection and input stream any longer just close them right after reading the content (before creating EncodedImage):
is.close();
is = null; // let the finally block know there is no need to try closing it
fcon.close();
fcon = null; // let the finally block know there is no need to try closing it
Minor points:
Also in the finally block it is worth set fcon = null; explicitly after you close it, I believe this can help old JVMs (BB uses Java 1.3 - rather old one) to decide quicker that the object is ready to be garbage collected.
I also believe that the order you close streams in the finally block may be important - I'd change to close is first and then fcon.

Problem reading an byte array into an object after being decoded from a string.

I'm trying to serialize and deserialize a byte array to a string using Base64 for as3.
Here is my code
public function Serialize(vector:Vector.<Action>):String
{
var bytes:ByteArray = new ByteArray();
var serialized:String = "";
registerClassAlias("Action", Action);
try { bytes.writeObject(vector); trace("Unserialized bytes:\n" + bytes + "\n"); }
catch (e:Error) { trace("Writing object Failed!!\n" + e); }
bytes.position = 0;
bytes.compress();
trace("Compressed bytes:\n" + bytes + "\n");
return Base64.encode(bytes);
}
public function Deserialize(serializedString:String):Vector.<Action>
{
var deserialized:ByteArray = new ByteArray();
var deserializedObj:Object = new Object();
var newVector:Vector.<Action> = new Vector.<Action>();
try { deserialized = Base64.decode(serializedString); trace("Deserialized bytes:\n" + deserialized + "\n"); }
catch (e:Error) { trace("Decoding Failed!!\n" + e); }
deserialized.position = 0;
deserialized.uncompress();
trace("Uncompressed bytes:\n" + deserialized + "\n");
try { deserializedObj = deserialized.readObject(); trace("Moving bytes into an object" + deserializedObj); }
catch (e:Error) { trace("Reading Object Failed!!\n" + e); }
for each(var a:Action in deserializedObj)
{
trace(a);
newVector.push(a);
}
return newVector;
}
I tested this and serializing works fine, but
Reading Object Failed!!
ArgumentError: Error #1063: Argument count mismatch on System::Action(). Expected 2, got 0.
is the error I get after calling deserializedObj = deserialized.readObject();
Should I be get that error if I'm just trying to put this into an object? I'm not trying to put it into an action class object yet, but if it is then the action it's getting doesn't have parameters that were originally inside.
It looks like Action has a constructor that takes two parameters (without defaults). readObject apparently can't handle constructing objects with non-default constructors.
Change Action so that its constructor parameters have defaults and see if that helps.
I have never seen that error System:Action
The only thing that I see that could be an issue.
try moving
deserialized.uncompress();
above
deserialized.position = 0;