Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, 19 January 2019

TravelTimeCalculator: Tying it All Together

TravelTimeHandler is now working in the sense that it collects directions from Google Directions (or casched from the internal SQLite database) and select the quickest option.

Implementation
I started with skeleton code that indicated what it was supposed to do using printouts to the logs.


The stubbed method. I'll replace the
console print statements with actual
code later.
After having the overall structure in place, I implemented the needed methods:

  • scanDirectionsForTap is activated when the user taps the map. It starts with a query to the database for any directions between the center of the map and the tapped location. If no results are found, it queries Google Directions for bicycling, driving, transit and walking.
  • getShortestDirectionFromDb queries the database for the shortest duration (or distance) between two points. It returns the value and an integer representing the mode.
  • saveDirectionsToDb saves the directions to the database
  • clearMarkers will clear the markers from the map (stub). I'll call this method when the map is moved.
  • addMarkers will add a marker to the map (stub)
  • getDirectionsFromUrl queries Google Directions for distance and duration for a couple of coordinates and a mode of transport. The response is handled in the over-ridden method onResponse. onResponse adds the result to the database. After that, it will query the database for the shortest distance/duration using getShortestDirectionFromDb.
  • readDirectionsFromJson extracts the relevant data from the JSON response from Google Directions.

Since the database handles only integers for the coordinates, I'll multiply the coordinates by 1000 and round them to integers when querying the database. 

The output from some queries is:
Initially, the app had no direction data for the coordinates.
After the query, the database was populated with the data.

Context 
One issue that I saw was applicationContext. When having code that uses context in another file than the mainActivity.java file, the app can't find it. The solution was to get the app context explicitly:


Remaining Work
I want to visualize the results with markers. I'll add one marker in the middle that represents the current location.

When the user taps on the map, I'll add a corresponding marker on the map. The marker will have a color or symbol that indicates the quickest transport mode (driving, transit, walking or bicycling).

When the user moves the map, the existing markers are cleared. The app should look for existing directions in the database and add corresponding markers automatically.

Saturday, 3 November 2018

TravelTimeCalculator: Hiding My API Key from Git

In the last blog post, I used a Google Directions API to get directions. In order to use more than one requests per day, an API key is needed.

API keys are used by applications to get access to several different online services.

Generally, it kind of cheap for Google Directions API: it will cost half a USD cent to query one api. Still, I'll need to reduce the requests for Google Directions and store the existing results to a local database. I'll elaborate more on that in the future.

When pushing my code to GIT, I need to make sure that no one will copy my key and freeload on my billing account. Luckily, this is easy to do.

As described by Varun Barad in his article at Medium.com, simply put the API keys in a file outside the GIT repo and point to that file using the Android gradle system.

For Python, it seems to be easier. Black Tech Diva has an instruction for that language.

Saturday, 27 October 2018

TravelTimeCalculator: Creating a Google Directions Request

After adding a button on the Google Maps view, I've added a listener to it that fetches the center coordinate for the view (cameraTarget).



If those coordinates are available, the app will build a string that will query the Google Directions API for biking between two coordinates:

https://maps.googleapis.com/maps/api/directions/json?origin=55.59,13.019&destination=55.6,13.019&mode=bicycling&key=<MY_API_KEY>

After typing the string into a web browser, I get:

In the next blog post, I'll send the request from the app and analyze the result string.

Saturday, 13 October 2018

TravelTimeCalculator: Adding Project to Github

After being able to add a numb button to the user interface, I've decided to add the project to my Github account: https://github.com/cutetrains/TravelTimeCalculator

Since I'm in a learning curve in Android design, the quality of the code and design of this app will be quite low. If you're looking for some advice from Android gurus, refer to the documentation or any of the thousands more skilled developers.

The app sets up a Google maps view with a button on top of that. (TODO: Move the button to the lower right of the view so that the user can press the button with the hand that holds the device)



When opening the app, the app fetches the last known location (TODO: Fetch also the current location, in case the phone has no last known location) and prints it to logcat. It also proposes eight other coordinates that surround the device.

If the user taps the button, there is code that reacts to that. Currently, it just prints a logcat message, but I'll make the app print the center coordinates of the map view and the zoom factor to logcat.

Sunday, 6 August 2017

TrafficControl: Possible Areas for Optimization

When designing software, it is often important to compromise between simplicity and performance. Optimizing source code can improve performance, but it will also make the software more complex and harder to debug and maintain in the future.

For TrafficControl, I've identified some areas where I can optimize it, if that will be needed later on:
  • Accessing QML items from C++: In the QML slot, the JavaScript is iterating over the QML object tree until it finds the item with the corresponding objectName. It should be possible to save the index for the particular QML item when creating it, and save the index so that C++ objects can access the QML item directly. 
  • Updating position of trains on tracks: Currently, the program is iterating through all coordinates to find wich two consecutive coordinates to interpolate between for every update. It should be possible to rmake the program remember the last coordinate and search from there.
  • Implementing model/view for the QML map: Explore whether this will improve the performance.
Before doing all that, I'll review, refactor and clean up the code.

Sunday, 11 June 2017

TrafficControl: Modifying Existing Station QML Items from C++

The blog posts has been scarse, due to positive news in my closest family. I'll be a busy family man for the coming decades but I'll keep writing on this blog.

When something happens to a station in the C++ part of the program, the corresponding QML item shall be modified. I got inspiration from a post on Andrew Jones' blog, regarding QML/C++ interactions using signals/slots.

Train::move() will trigger signal that will be caught by the QML part and update the map.
  • A train enters a station
  • A signal is trigged by train::move(), containing the station name, the train name and a description of the event
  • A slot in the QML part recieves the signal and extracts the information.
  • The corresponding QML item is updated
The new signal is called stationChangedSignal, and will contain three qVariants:
  1. The first will always contain the name of the station that is changing
  2. The second parameter will define what has happened (in this case: "train arrival")
  3. The third parameter will define any other items/objects (in this case, the train name)
In this case, I'll let the train::runningToOpeningState() emit a signal:
stationChangedSignal("LundC", "train arrival",  "Hedy_Lamarr")

This signal will tell the QML part that a train named "Hedy_Lamarr" has arrived to the station LundC".

The current commit, 1c198ff, has introduced a signal without any parameters. I still have some problems parsing a signal containing qVariant data to the QML javascript. More about that in the next blog post.

Thursday, 25 May 2017

TrafficControl: Recap of the QML Station Handling

The python script TrackStationConnector reads a KML file containing a station.

A KML file contains station information as a placemark.


The script TrackStationConnector extracts track information and converts it to a proper input format.


TrafficControl has a function that is analysing the input file, and if it finds a station with coordinates, it will call a function that creates the QML station

The QML item iscreated by calling a JavaScript in the QML part

This code is probably redundant, I will try to remove it later.

Finally, the JavaScript in a separate file creates the QML item.


Thursday, 16 March 2017

TrafficControl: Adding QML Components Dynamically

To be useful, TrafficControl needs to present the stations on an interactive map. The program logic is currently implemented in C++ with some Qt Graphical User interfaces using model-view relations.

The original presentation of the stations and tracks, that were imported from a KML file.

A part of the user interface will be based on QML, that imports a map from OpenStreet maps. QML is a design language where one can add graphical elements easily. I will describe a simple QML demo program later and publish it on my github account. 

The challenge for me has been to add components in QML dynamically from C++, when stations or tracks are found. The placemarks below are from Google Earth/KML.

The yellow placemarks are representing stations.
The stations has been identified and their coordinate has been sent to the QML part of the program,

The stations has been identified by trafficControl and dynamically added as circles

Some of the next steps will be:
  • Modifying the different stations individually
  • Adding tracks
  • Adding trains
  • Showing status when hovering the mouse pointer over the items
  • Modifying the components regarding their statuses
  • Investigating model/view for QML map items

Thursday, 6 November 2014

TrafficControl: Looking into Javascript

The last weeks, I've spent time learning Javascript. It is very similar to C++ and, obviously, Java so the learning gap has been quite small.

I'm investigating if I can use Javascript for trafficControl, using Google Maps/Earth to handle the maps with kml files. Kml files contains the coordinates for the tracks and the stations.

As a first step, I created a Javascript that loaded a kml file to a Google Earth window and displayed that on a web page. This was quite easy with the help from Google Earth API. There, one can find some very helpful examples: https://developers.google.com/earth/


The next step was to make the Javascript analyse the coordinates in the kml file. This gave me some headache as the kml file needs to be loaded into the script itself, and this isn't allowed for web security reasons. I'll discuss that in the next post.

For web programming I can recommend http://www.w3schools.com/ with their excellent tutorials in Javascript, AJAX, JQuery, html and several other technologies. For demonstations of their code, they have a "Try it Yourself" feature, where it is possible to modify their examples and explore the code.