When I enter the panel at https://console.cloud.google.com/google/maps-apis/overview and create a key and then add it to the application, the route is laid. After I exit and re-enter the application, the route is no longer laid. There is nothing in the logs either.
I have already tried all the methods, I checked the code 100 times, but I cannot find any errors. Help me please.
public class DirectionFinder {
private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?";
private static final String GOOGLE_API_KEY = "this is my key";
private DirectionFinderListener listener;
private String origin;
private String destination;
public DirectionFinder(DirectionFinderListener listener, String origin, String destination) {
this.listener = listener;
this.origin = origin;
this.destination = destination;
}
public void execute() throws UnsupportedEncodingException {
listener.onDirectionFinderStart();
new DownloadRawData().execute(createUrl());
}
private String createUrl() throws UnsupportedEncodingException {
String urlOrigin = URLEncoder.encode(origin, "utf-8");
String urlDestination = URLEncoder.encode(destination, "utf-8");
return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&key=" + GOOGLE_API_KEY;
}
private class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}
return decoded;
}
I want to lay the route.
You don't seem to be adding your points to a map. Typically, you would add your points to a PolylineOptions object, then add them to your map:
pathDynamic = new PolylineOptions().width(15).color(Color.RED);
pathDynamic.add(theLatLng); //add a bunch of points
if (mMap != null) {
mMap.addPolyline(pathDynamic);
}
Related
I have one JSON file and having some issue in it. When parsing the json file I will get the ParserException. From parser exception I have extracted the position where the is problem.
Now I want the line number of the that particular position in file.
JSONObject json;
try {
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
json = (JSONObject) new JSONParser().parse(data);
return json;
} catch (ParseException e) {
this.log.logException(e);
int position = e.getPosition();
String reason = e.getUnexpectedObject().toString();
return new JSONObject();
}
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
try {
return new JSONParser().parse(data);
} catch (ParseException e) {
String lineAndColumn = lineAndColumn(data, e, 4);
...;
return new JSONObject();
}
public static String lineAndColumn(String text, ParseException e, int tabSize) {
int position = e.getPosition();
int lineNo = 1 + (int) text.substring(0, position).codePoints()
.filter(cp -> cp == '\n')
.count();
int columnNo = 1 + text.substring(0, position).lastIndexOf('\n') + 1; // no \n okay too.
// Tabs
int cI = 0;
for (int i = 0; i < columnNo - 1; ++i) {
if (text.charAt(posion - (columnNo - 1) + i) == '\t') {
cI += tabSize;
cI %= tabSize;
} else {
++cI;
}
}
columnNo = cI + 1;
return String.format("%d:%d"), lineNo, ColumnNo);
}
I'm getting the error below:
Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
I am trying to get routes from google map using places API using the following code.
private void getDirection() {
currentPosition = new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude());
String requestApi = null;
try{
requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+
"mode=driving&"+
"transit_routing_preference=less_driving&"+
"origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+
"destination="+destination+"&"+
"key="+getResources().getString(R.string.google_direction_api);
Log.d("HAMZA",requestApi); //Print URL for debugging purpose.
mService.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for(int i =0;i<jsonArray.length();i++)
{
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
//Adjusting bounds
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng:polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds,2);
mMap.animateCamera(mCameraUpdate);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.GRAY);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(JointType.ROUND);
polylineOptions.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptions);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(5);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size()-1))
.title("Pickup Location"));
//Animation
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0,100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int)valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int)(size * percentValue/100.0f);
List<LatLng> p = points.subList(0,newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
handler = new Handler();
index=-1;
next=1;
handler.postDelayed(drawPathRunnable,3000);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(Welcome.this,""+t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
and using this parser from jeffreysambells
public class DirectionJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l <list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Error occurs when I search something using places API and select the result I want.
Im new/learning Java and Android, and attempting to make a simple weather app which tells me the weather in my current location. I've got the basics figured out and I'm using OpenWeatherMap APIs - all good here.
What I'm trying to do is the following:
- When API returns to me that the weather is, for example, 'broken clouds', or 'heavy rain', I want to set an ImageView to a picture of, say broken clouds, or heavy rain.
I just cant seem to get the ImageView to take the images (which are in my Drawable folder) - I have tried using setImageResource, tried setImageDrawable, among others. Any pointers? What am I missing?
Here is my code (the important bits):
public class DownloadHtml extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
String tempInfo = jsonObject.getJSONObject("main").getString("temp");
String windInfo = jsonObject.getJSONObject("wind").getString("deg");
JSONArray weatherArr = new JSONArray(weatherInfo);
for (int i = 0; i < weatherArr.length(); i++) {
TextView weatherTextView = findViewById(R.id.weatherTextView);
weatherTextView.setText("");
JSONObject jsonPart = weatherArr.getJSONObject(i);
String description = jsonPart.getString("description");
weatherTextView.setText(description);
iv = findViewById(R.id.imageView2);
if (description == "clear sky") iv.setImageResource(R.drawable.clear_skies);
else if (description == "few clouds")
iv.setImageResource(R.drawable.few_clouds);
else if (description == "scattered clouds")
iv.setImageResource(R.drawable.scattered_clouds);
else if (description == "broken clouds")
iv.setImageResource(R.drawable.broken_clouds);
else if (description == "shower rain")
iv.setImageResource(R.drawable.shower_rain);
else if (description == "rain") iv.setImageResource(R.drawable.heavy_rain);
else if (description == "thunderstorm")
iv.setImageResource(R.drawable.thunderstorm);
else if (description == "snow") iv.setImageResource(R.drawable.snow);
else if (description == "mist") iv.setImageResource(R.drawable.mist);
Log.i("description", jsonPart.getString("description"));
if (description != null) {
locationManager.removeUpdates(locationListener);
}
}
for (int f = 0; f < tempInfo.length(); f++) {
TextView weatherTextView3 = findViewById(R.id.weatherTextView3);
weatherTextView3.setText("");
String tempString = tempInfo + " degrees celcius.\n";
weatherTextView3.setText(tempString);
Log.i("temp: ", tempInfo);
if (tempString != null) {
locationManager.removeUpdates(locationListener);
f = 500;
}
}
for (int j = 0; j < windInfo.length(); j++) {
TextView weatherTextView2 = findViewById(R.id.weatherTextView2);
weatherTextView2.setText("");
// assign text to wind direction
double windDegrees = Double.valueOf(windInfo);
if ((windDegrees > 0) && (windDegrees < 90)) {
String windString = "A North East Wind.\n";
weatherTextView2.setText(windString);
Log.i("Wind: ", windInfo);
}
if ((windDegrees >= 90) && (windDegrees < 180)) {
String windString = "A South East Wind.\n";
weatherTextView2.append(windString);
Log.i("Wind: ", windInfo);
}
if ((windDegrees >= 180) && (windDegrees < 270)) {
String windString = "A South West Wind.\n";
weatherTextView2.append(windString);
Log.i("Wind: ", windInfo);
}
if ((windDegrees >= 270) && (windDegrees < 360)) {
String windString = "A North West Wind.\n";
weatherTextView2.append(windString);
Log.i("Wind: ", windInfo);
}
if (windInfo != null) {
locationManager.removeUpdates(locationListener);
j = 500;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You just accidentally used == to compare strings :)
Use description.equals("clear sky") instead of description == "clear sky"
I have huge .csv files (the biggest one, 72mb) that I need to load to my Android App. They contain matrices e.g [7500x1000], which I later use to multiply another one. Because their are too big to read them at one time () I'm reading line after line and perform some multiplication. I tested this on Nexus 4 and It took something about 15 minutes to do everything. When I copied the code from Android project to JAVA one(the only difference is that in Android i'm using Bitmap and in JAVA BufferedImage) and ran this as java application it took few seconds. Do you have any idea why is so and how to shorten this time? Here Is my code:
Android:
public class NetworkThread extends Thread {
private static boolean threadIsWorking = false;
private Context context;
private SQLiteHandler sql;
private static NetworkThread REFERENCE = null;
private String w1 = "w1.csv";
private String w2 = "w2.csv";
private String w3 = "w3.csv";
private String w4 = "w4.csv";
String NEURON_PATH = "/data/data/com.ZPIProject/neuronFiles/";
public static NetworkThread getInstance(Context context, SQLiteHandler sql) {
if (REFERENCE == null)
REFERENCE = new NetworkThread(context, sql);
return REFERENCE;
}
private NetworkThread(Context context, SQLiteHandler sql) {
this.context = context;
this.sql = sql;
}
#Override
public void start() {
if (!threadIsWorking) {
threadIsWorking = true;
try {
Log.i("MATRIX", "THREAD ID: " + Thread.currentThread().getId());
Bitmap bit = BitmapFactory.decodeResource(context.getResources(), R.drawable.aparat_small);
double[] imageInfo = ImageUtils.getImageInfo(bit);
copyNeuronWeightsToMemoryOnPhone();
double[] m4 = multiplyImageWithNeuronWeights(imageInfo);
List<WeightWithId> best10 = findBest10Results(m4);
for (int i = 0; i < best10.size(); i++) {
Log.e("IDS", best10.get(i).getId() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private List<WeightWithId> findBest10Results(double[] m4) throws SQLException, CloneNotSupportedException {
List<WeightWithId> best10 = new ArrayList<WeightWithId>(20);
for (int j = 0; j < 19; j++) {
Map<Integer, double[]> readDescriptions = sql.getDescriptionForShoeId(j * 100, j * 100 + 100);
List<WeightWithId> distances = new ArrayList<WeightWithId>(100);
for (Integer i : readDescriptions.keySet()) {
double dist = dist(m4, readDescriptions.get(i));
distances.add(new WeightWithId(i, dist));
}
Collections.sort(distances);
for (int i = 0; i < 10; i++) {
best10.add(distances.get(i).clone());
}
Collections.sort(best10);
if (best10.size() > 10) {
for (int i = 10; i < best10.size(); i++) {
best10.remove(i);
}
}
}
return best10;
}
private double[] multiplyImageWithNeuronWeights(double[] imageInfo) throws IOException {
Log.i("MATRIX MULTIPLY", "M1");
double[] m1 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w1, imageInfo, 1000, false);
Log.i("MATRIX MULTIPLY", "M2");
double[] m2 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w2, m1, 500, false);
Log.i("MATRIX MULTIPLY", "M3");
double[] m3 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w3, m2, 250, false);
Log.i("MATRIX MULTIPLY", "M4");
return MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w4, m3, 50, true);
}
private void copyNeuronWeightsToMemoryOnPhone() throws IOException {
Log.i("MATRIX COPY", "W1");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w1, context);
Log.i("MATRIX COPY", "W2");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w2, context);
Log.i("MATRIX COPY", "W3");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w3, context);
Log.i("MATRIX COPY", "W4");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w4, context);
}
private double dist(double[] a, double[] b) {
double result = 0;
for (int i = 0; i < a.length; i++)
result += (a[i] - b[i]) * (a[i] - b[i]);
return result;
}
}
Matrix Operations:
public class MatrixMaker {
public static double[] multiplyImageInfoWithCsvMatrix(String csvFilePath, double[] imageInfo, int expectedSize, boolean lastOne) throws IOException {
InputStream inputStream = new FileInputStream(new File(csvFilePath));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
//counter - to which position calculated value should be setted
int counter = 0;
//result array
double[] multipliedImageInfoWithCsvMatrix = new double[expectedSize + 1];
//declaration of array for read line (parsed into double array)
double[] singleLineFromCsv = new double[imageInfo.length];
while ((line = bufferedReader.readLine()) != null) {
//splitting and parsing values from read line
String[] splitted = line.split(",");
for (int i = 0; i < splitted.length; i++) {
singleLineFromCsv[i] = Double.valueOf(splitted[i]);
}
//multiply imageInfo array with single row from csv file
multipliedImageInfoWithCsvMatrix[counter] = multiplyOneRow(imageInfo, singleLineFromCsv);
//ugly flag 'lastOne' needed to other business case
if (!lastOne) {
multipliedImageInfoWithCsvMatrix[counter] = 1d / (1 + Math.exp(-multipliedImageInfoWithCsvMatrix[counter]));
}
counter++;
//logging progress
if (counter % 100 == 0)
Log.i("MULTIPLY PROGRESS", counter + " " + System.currentTimeMillis());
}
if (!lastOne)
multipliedImageInfoWithCsvMatrix[expectedSize] = 1d;
bufferedReader.close();
inputStream.close();
return multipliedImageInfoWithCsvMatrix;
}
private static double multiplyOneRow(double first[], double second[]) {
double result = 0d;
for (int i = 0; i < first.length; i++) {
result += first[i] * second[i];
}
return result;
}
}
onCreate in one of Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
final SQLiteHandler sql = new SQLiteHandler(this);
sql.init();
NetworkThread.getInstance(this, sql).start();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
JAVA:
Multiply equivalent of Matrix Maker
import java.io.*;
public class Multiply {
public static double[] multiplyMatrixWithCsvMatrix(String csvFilePath, double[] imageInfo,
int expectedSize, boolean lastOne) throws IOException {
InputStream inputStream = new FileInputStream(new File(csvFilePath));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
// counter - to which position calculated value should be setted
int counter = 0;
// result array
double[] multipliedImageInfoWithCsvMatrix = new double[expectedSize + 1];
// declaration of array for read line (parsed into double array)
double[] singleLineFromCsv = new double[imageInfo.length];
while ((line = bufferedReader.readLine()) != null) {
// splitting and parsing values from read line
String[] splitted = line.split(",");
for (int i = 0; i < splitted.length; i++) {
singleLineFromCsv[i] = Double.valueOf(splitted[i]);
}
// multiply imageInfo array with single row from csv file
multipliedImageInfoWithCsvMatrix[counter] = multiplyOneRow(imageInfo, singleLineFromCsv);
// ugly flag 'lastOne' needed to other business case
if (!lastOne) {
multipliedImageInfoWithCsvMatrix[counter] = 1d / (1 + Math
.exp(-multipliedImageInfoWithCsvMatrix[counter]));
}
counter++;
// logging progress
if (counter % 100 == 0)
System.out.println(counter + " " + System.currentTimeMillis());
}
if (!lastOne)
multipliedImageInfoWithCsvMatrix[expectedSize] = 1d;
bufferedReader.close();
inputStream.close();
return multipliedImageInfoWithCsvMatrix;
}
private static double multiplyOneRow(double first[], double second[]) {
double result = 0d;
for (int i = 0; i < first.length; i++) {
result += first[i] * second[i];
}
return result;
}
}
Executable class
public class MRunner {
private static final int RED_INDEX = 0;
private static final int GREEN_INDEX = 2500;
private static final int BLUE_INDEX = 5000;
private static final String w1 = "w1.csv";
private static final String NEURON_PATH = "C:\\Users\\Vortim\\Desktop\\";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Multiply.multiplyMatrixWithCsvMatrix(NEURON_PATH + w1, getImageInfo(ImageIO
.read(new File("C:\\Users\\Vortim\\git\\MatrixMaker\\but.png"))), 1000,
false);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static double[] getImageInfo(BufferedImage source) {
double[] result = new double[7501];
int width = source.getWidth();
int height = source.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x == 0) {
result[y + RED_INDEX] = 255d;
result[y + GREEN_INDEX] = 255d;
result[y + BLUE_INDEX] = 255d;
} else if (y == 0) {
result[x * 50 + RED_INDEX] = 255d;
result[x * 50 + GREEN_INDEX] = 255d;
result[x * 50 + BLUE_INDEX] = 255d;
} else {
int pixel = source.getRGB(x, y);
double r = (pixel) >> 16 & 0xff;
double g = (pixel) >> 8 & 0xff;
double b = (pixel) & 0xff;
result[x * y + RED_INDEX] = 1d - (r / 255d);
result[x * y + GREEN_INDEX] = 1d - (g / 255d);
result[x * y + BLUE_INDEX] = 1d - (b / 255d);
}
}
}
result[7500] = 1;
return result;
}
}
My application can give a path/direction using JSON. How can I change in different colors in on path given by JSON?
For example, form point A to point B is red, B to C is yellow, C to D is green, and so on.
The code is:
Getting points in JSON.
private void parsing(GeoPoint start, GeoPoint end) throws ClientProtocolException, IOException, JSONException, URISyntaxException{
HttpClient httpclient = new DefaultHttpClient();
StringBuilder urlstring = new StringBuilder();
urlstring.append("https://maps.googleapis.com/maps/api/directions/json?origin=")
.append(Double.toString((double)start.getLatitudeE6()/1E6)).append(",").append(Double.toString((double)start.getLongitudeE6()/1E6)).append("&destination=")
.append(Double.toString((double)end.getLatitudeE6()/1E6)).append(",").append(Double.toString((double)end.getLongitudeE6()/1E6))
.append("&sensor=false");
//urlstring.append("http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=true");
url = new URI(urlstring.toString());
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = null;
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
String result = sb.toString();
JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<GeoPoint> pointToDraw = decodePoly(encodedString);
//Added line:
mv_mapview.getOverlays().add(new RoutePathOverlay(pointToDraw));
}
List of Geopoints given by JSON.
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6), (int) (((double) lng / 1E5) * 1E6));
//n = new Node(p,);
poly.add(p);
}
return poly;
}
and Overlay class
public class RoutePathOverlay extends Overlay {
private int _pathColor;
private final List<GeoPoint> _points;
private boolean _drawStartEnd;
public RoutePathOverlay(List<GeoPoint> points) {
this(points, Color.GREEN, true);
}
public RoutePathOverlay(List<GeoPoint> points, int pathColor, boolean drawStartEnd) {
_points = points;
_pathColor = pathColor;
_drawStartEnd = drawStartEnd;
}
private void drawOval(Canvas canvas, Paint paint, Point point) {
Paint ovalPaint = new Paint(paint);
ovalPaint.setStyle(Paint.Style.FILL_AND_STROKE);
ovalPaint.setStrokeWidth(2);
int _radius = 6;
RectF oval = new RectF(point.x - _radius, point.y - _radius, point.x + _radius, point.y + _radius);
canvas.drawOval(oval, ovalPaint);
}
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
Projection projection = mapView.getProjection();
if (shadow == false && _points != null) {
Point startPoint = null, endPoint = null;
Path path = new Path();
//We are creating the path
for (int i = 0; i < _points.size(); i++) {
GeoPoint gPointA = _points.get(i);
Point pointA = new Point();
projection.toPixels(gPointA, pointA);
//if()
if (i == 0) { //This is the start point
startPoint = pointA;
path.moveTo(pointA.x, pointA.y);
} else {
if (i == _points.size() - 1)//This is the end point
endPoint = pointA;
path.lineTo(pointA.x, pointA.y);
}
}
Paint paint = new Paint();
paint.setAntiAlias(true);
// if(){
paint.setColor(_pathColor);
//}
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setAlpha(90);
if (getDrawStartEnd()) {
if (startPoint != null) {
drawOval(canvas, paint, startPoint);
}
if (endPoint != null) {
drawOval(canvas, paint, endPoint);
}
}
if (!path.isEmpty())
canvas.drawPath(path, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
public boolean getDrawStartEnd() {
return _drawStartEnd;
}
public void setDrawStartEnd(boolean markStartEnd) {
_drawStartEnd = markStartEnd;
}
}
You are decoding only overview_polyline.
Each part of the trip (steps array in response JSON) is defined as
{
distance: {
text: "89 m",
value: 89
},
duration: {
text: "1 min",
value: 8
},
end_location: {
lat: 45.51101000000001,
lng: -73.5545
},
html_instructions: "Enter <b>Rue Saint Antoine E</b>",
polyline: {
points: "cvwtG~d}_MaBs#s#W"
},
start_location: {
lat: 45.51026,
lng: -73.55488000000001
},
travel_mode: "DRIVING"
},
As you can see there is a polyline for each step. Have you tried decoding single steps, store them in an array and then visualize each section (using a different color for each part of the trip)?
This will give you a resolution of a "sector" of the trip, but it could be a good start point.
OR you could try to generate an array for every secton of overview_polyline (since its defined by points you could create single lines: if your polyline passes trough A, B, C and D you can define 3 segments A-B B-C C-D).
I don't know how much this (generate and visualize an overlay with a lot of pieces in it) will affect performance since i never used Maps API in this way (i used it to get ETA for some trip) so i'm just guessing :D