File: SearchMapillaryFunction.java

package info (click to toggle)
gpsprune 19.2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,516 kB
  • sloc: java: 42,704; sh: 25; makefile: 24; python: 15
file content (231 lines) | stat: -rw-r--r-- 6,766 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package tim.prune.function.search;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import tim.prune.App;
import tim.prune.I18nManager;
import tim.prune.data.DataPoint;
import tim.prune.data.Distance;
import tim.prune.data.Field;
import tim.prune.data.Latitude;
import tim.prune.data.Longitude;
import tim.prune.data.SourceInfo;
import tim.prune.data.UnitSetLibrary;
import tim.prune.load.MediaLinkInfo;

/**
 * Function to search mapillary for photos
 */
public class SearchMapillaryFunction extends GenericDownloaderFunction
{
	/** Maximum number of results to get */
	private static final int MAX_RESULTS = 20;


	/**
	 * Constructor
	 * @param inApp app object
	 */
	public SearchMapillaryFunction(App inApp)
	{
		super(inApp);
	}

	@Override
	public String getNameKey() {
		return "function.mapillary";
	}

	@Override
	protected String getColumnKey(int inColNum)
	{
		if (inColNum == 0) return "dialog.wikipedia.column.name";
		return "dialog.wikipedia.column.distance";
	}

	/**
	 * Run method, for searching in a separate thread
	 */
	public void run()
	{
		_statusLabel.setText(I18nManager.getText("confirm.running"));
		// Get coordinates from current point (if any) or from centre of screen
		double lat = 0.0, lon = 0.0;
		DataPoint currentPoint = _app.getTrackInfo().getCurrentPoint();
		if (currentPoint == null)
		{
			double[] coords = _app.getViewport().getBounds();
			lat = (coords[0] + coords[2]) / 2.0;
			lon = (coords[1] + coords[3]) / 2.0;
		}
		else
		{
			lat = currentPoint.getLatitude().getDouble();
			lon = currentPoint.getLongitude().getDouble();
		}

		// Construct URL
		final String urlString = "http://api.mapillary.com/v1/im/close?lat="
			+ lat + "&lon=" + lon + "&distance=1000&limit=" + MAX_RESULTS;
		//System.out.println(urlString);
		InputStream inStream = null;
		try
		{
			inStream = new URL(urlString).openStream();
			StringBuilder sb = new StringBuilder();
			int ch = 0;
			while ((ch = inStream.read()) >= 0)
			{
				sb.append((char) ch);
			}
			//System.out.println("Got answer: '" + sb.toString() + "'");

			ArrayList<SearchResult> resultList = new ArrayList<SearchResult>();
			for (String result : sb.toString().split("\\},\\{"))
			{
				//System.out.println("Result: '" + result + "'");
				SearchResult sr = new SearchResult();
				for (String prop : result.split(","))
				{
					String key = getKey(prop);
					if (key == null) {continue;}
					if (key.equals("key"))
					{
						final String value = getValue(prop);
						sr.setDownloadLink("http://images.mapillary.com/" + value + "/thumb-1024.jpg");
						sr.setWebUrl("http://www.mapillary.com/map/im/" + value);
						sr.setTrackName(value);
					}
					else if (key.equals("lat")) {
						sr.setLatitude(getValue(prop));
					}
					else if (key.equals("lon")) {
						sr.setLongitude(getValue(prop));
					}
				}

				if (sr.getLatitude() != null && sr.getLongitude() != null && sr.getTrackName() != null)
				{
					// Calculate distance away from current point and set this in sr.setLength
					DataPoint resultPoint = new DataPoint(new Latitude(sr.getLatitude()), new Longitude(sr.getLongitude()), null);
					if (resultPoint.isValid() && currentPoint != null && currentPoint.isValid())
					{
						double radianDist = DataPoint.calculateRadiansBetween(currentPoint, resultPoint);
						double metresAway = Distance.convertRadiansToDistance(radianDist, UnitSetLibrary.UNITS_METRES);
						sr.setLength(metresAway);
					}

					// If there's a valid result, add it to the temporary list
					if (sr.getTrackName() != null) {
						resultList.add(sr);
					}
				}
			}
			// Add all the results to the table model in one go
			if (!resultList.isEmpty()) {
				_trackListModel.addTracks(resultList);
			}
		}
		catch (Exception e) {
			_errorMessage = e.getClass().getName() + " - " + e.getMessage();
		}
		// Close stream and ignore errors
		try {
			inStream.close();
		} catch (Exception e) {}

		// Set status label according to error or "none found", leave blank if ok
		if (_errorMessage == null && _trackListModel.isEmpty()) {
			_errorMessage = I18nManager.getText("dialog.mapillary.nonefound");
		}
		_statusLabel.setText(_errorMessage == null ? "" : _errorMessage);
	}

	/**
	 * From a JSON key:value string, return just the key
	 * @param inString string to parse
	 * @return just the key without the surrounding quotes, or null if not found
	 */
	private static String getKey(String inString)
	{
		if (inString == null || inString.equals("")) {return null;}
		final int colonPos = inString.indexOf(':');
		if (colonPos <= 0) {return null;}
		int startPos = 0;
		char c;
		while ((c = inString.charAt(startPos)) == '['
			|| c == '{' || c == '\"')
		{
			startPos++;
		}
		int endPos = colonPos;
		while ((c = inString.charAt(endPos-1)) == '\"')
		{
			endPos--;
		}
		return inString.substring(startPos, endPos);
	}

	/**
	 * From a JSON key:value string, return just the value
	 * @param inString string to parse
	 * @return just the value without the surrounding quotes
	 */
	private static String getValue(String inString)
	{
		final int colonPos = inString.indexOf(':');
		if (colonPos <= 0 || colonPos >= inString.length()) {return null;}
		int startPos = colonPos+1;
		char c;
		while ((c = inString.charAt(startPos)) == '\"')
		{
			startPos++;
		}
		int endPos = inString.length()-1;
		while ((c = inString.charAt(endPos-1)) == '\"'
			|| c == '}' || c == ']')
		{
			endPos--;
		}
		return inString.substring(startPos, endPos);
	}

	@Override
	protected void loadSelected()
	{
		// Find the row(s) selected in the table and get the corresponding track
		int numSelected = _trackTable.getSelectedRowCount();
		if (numSelected < 1) return;
		int[] rowNums = _trackTable.getSelectedRows();

		String[][] pointData = new String[numSelected][];
		String[]   linkArray = new String[numSelected];

		// Loop over each of the selected points
		for (int i=0; i<numSelected; i++)
		{
			pointData[i] = new String[3]; // lat, long, segment
			int rowNum = rowNums[i];
			if (rowNum >= 0 && rowNum < _trackListModel.getRowCount())
			{
				SearchResult result = _trackListModel.getTrack(rowNum);
				//String url = result.getDownloadLink();
				pointData[i][0] = result.getLatitude();
				pointData[i][1] = result.getLongitude();
				pointData[i][2] = "1"; // all points have a new segment
				linkArray[i]    = result.getDownloadLink();
			}
		}
		// Prepare the data for the app
		final Field[] fields = {Field.LATITUDE, Field.LONGITUDE, Field.NEW_SEGMENT};
		_app.autoAppendNextFile();
		_app.informDataLoaded(fields, pointData, null, new SourceInfo("mapillary", SourceInfo.FILE_TYPE.JSON),
			null, new MediaLinkInfo(linkArray));

		// Close the dialog
		_cancelled = true;
		_dialog.dispose();
	}
}