Tuesday, May 29, 2012

How to use GPS location services and Google Static Map API in J2ME MIDlets

oday, most mobile devices come with a GPS module or can connect to one using Bluetooth services. These devices come with support for the Location API for J2ME under JSR-179 that allow J2ME MIDlets applications to query the GPS module for geo-location coordinates. Also mobile applications integrate location based services and one increasingly used it to provide maps images using Google Maps or Google Static Maps. The later is accessible through Google Static Maps API V2, which is an open and free service (no longer requires a Maps API key) and more efficient as it minimizes network transfers.
In this article it is described and developed a fully MIDlet application that gets coordinates from the mobile device GPS module and use them to display a Google static map for that location. The application can be tested on the emulator or on a real device that has a GPS module incorporated.

You can download the full source code, including a sample test MIDlet.
If you have a mobile device that doesn’t have a GPS incorporated, this solution will not work because the J2ME Location API doesn’t have methods for connecting through Bluetooth to that external module. In this case, you need another solution (I will post it in another article) that
  • uses the Bluetooth API (JSR 82) to discover and to connect to the external GPS module;
  • parse the received GPS NMEA strings.

How to use J2ME Location API (JSR-179) and get the GPS coordinates

 

Midlet that displays GPS coordinates


In order to communicate with the phone GPS module and get data regarding coordinates, course, altitude or speed we need classes from javax.microedition.location.* package:
  • create a javax.microedition.location.Criteria instance, used to select the location provider; although there are multiple options (described by the JSR-179 documentation), their default values are the least restrictive; in this example we choose explicitly to allow a cost for the service (it’s free) and we don’t have a power consumption requirement; this step is not so important because the device has one GPS module and these are the criteria for selecting between multiple modules;
import javax.microedition.location.*;
...
        Criteria criteria = new Criteria();
        //same as default value
        criteria.setCostAllowed(true);
        //same as default value
        criteria.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);


  • obtain the location provider reference, a LocationProvider instance, using previous defined criteria and use it to query the GPS module for the current location; the getLocation() method has a timeout parameter indication how long we are willing to wait (seconds) for the data;
  • get the coordinates and extract the latitude and longitude; Attention ! the coordinates are returned as double and only the CLDC 1.1 supports floating point data processing (set the device configuration to CLDC 1.1 for this project because CLDC 1.0 does not support double type):


LocationProvider provider = null;
double latitude;
double longitude;
try {
	//get the location provider
        provider = LocationProvider.getInstance(criteria);
	//set a timeout of 60 seconds
        Location location = provider.getLocation(60);
	//get the coordinates
        Coordinates coordinates = location.getQualifiedCoordinates();
 
        if (coordinates != null) {
            //get the latitude and longitude of the coordinates
            latitude = coordinates.getLatitude();
            longitude = coordinates.getLongitude();
        } else {
            //no coordinates
        }
    } catch (LocationException ex) {
        System.out.println("Problems with location provider ! " +
		ex.getMessage());
        ex.printStackTrace();
    } catch (InterruptedException ex) {
	System.out.println(ex.getMessage());
        ex.printStackTrace();
    }
 
 
In the final application, the previous code sample is part of the getGPSData() method. This method defines a inner class that extends Thread because we want to query the GPS module on another thread than the main one. In this way, the application will respond to commands while it is waiting for the GPS to respond.

How to get GPS data on regular intervals

If you want to develop a J2ME application that will receive GPS coordinates on regular intervals (not the case for this example) you must define a handler used by the LocationProvider to notify the application. To do this, you must implement the LocationListener interface that has 2 abstract methods:
  • locationUpdated(LocationProvider provider, Location location) – method called by the provider at regular intervals to provide the current location;
  • providerStateChanged(LocationProvider provider, int newState) – method called by the provider to announce if its new state (LocationProvider.OUT_OF_SERVICE, LocationProvider.AVAILABLE, LocationProvider.TEMPORARILY_UNAVAILABLE);

public void locationUpdated(LocationProvider arg0, Location arg1) {
        if (arg1 != null && arg1.isValid()) {
            //get the coordinates
            Coordinates coordinates = arg1.getQualifiedCoordinates();
 
            if (coordinates != null) {
                //get the latitude and longitude of the coordinates.
                latitude = coordinates.getLatitude();
                longitude = coordinates.getLongitude();
 
            } else {
                //no valid coordinates
            }
        }
    }
 
    public void providerStateChanged(LocationProvider arg0, int arg1) {
        if (arg1 == LocationProvider.OUT_OF_SERVICE ||
                arg1 == LocationProvider.TEMPORARILY_UNAVAILABLE) {
            System.out.println("GPS inactive");
        }
    }
For setting the listener and to receive updates on location, we must register the listener using setLocationListener(LocationListener listener,int interval,int timeout,int maxAge) method:
	provider.setLocationListener(this, 60, -1, -1);
For the last call, the application will receive GPS updates at each 60 seconds with default timeout and max Age.

If you want to stop the updates (this consumes battery power), this is done calling one again the setLocationListener() method:
	provider.setLocationListener(null, -1, -1, -1);

How to use Google Static Map API

Google Static Maps is a free service offered by Google to developers that want to embed maps into their applications based on URL parameters sent through a simple HTTP query string without requiring JavaScript or any dynamic page loading. The service sends an image as response.
So, in order to get an 300×300 pixels map image for the 44.435251 latitude and 26.1024 longitude, with a moderate zoom, you make a HTTP request using:
http://maps.google.com/maps/api/staticmap?center=44.435251,26.1024&zoom=14&size=300×300&sensor=false

Link: How to use GPS location services and Google Static Map API in J2ME MIDlets _ IT&C Solutions

 

Wednesday, May 23, 2012

How to Create a Horizontal Dropdown Menu with HTML, CSS and jQuery

The Basics

 

Let's start with the basic HTML structure of the menu:
1
2
3
4
5
6
7
<ul id="coolMenu">
<li><a href="#">Lorem</a></li>
<li><a href="#">Mauricii</a></li>
<li><a href="#">Periher</a></li>
<li><a href="#">Tyrio</a></li>
<li><a href="#">Quicumque</a></li>
</ul>
A menu consists of an unordered list, and each list item contains a link with the text. Don’t create unnecessary divs. You don’t need any.
To add a sub menu simply nest another unordered list inside the item that's going to have the sub menu, like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<ul id="coolMenu">
    <li><a href="#">Lorem</a></li>
    <li><a href="#">Mauricii</a></li>
    <li>
        <a href="#">Periher</a>
        <ul>
            <li><a href="#">Hellenico</a></li>
            <li><a href="#">Genere</a></li>
            <li><a href="#">Indulgentia</a></li>
        </ul>
    </li>
    <li><a href="#">Tyrio</a></li>
    <li><a href="#">Quicumque</a></li>
</ul>
As you can see, creating the structure is very simple. This is how it should look in your browser at this stage:


There are multiple ways to set up the CSS for a horizontal menu. After many years I found that this is the quickest and cleanest way to do it:
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
#coolMenu,
#coolMenu ul {
    list-style: none;
}
#coolMenu {
    float: left;
}
#coolMenu > li {
    float: left;
}
#coolMenu li a {
display: block;
    height: 2em;
    line-height: 2em;
    padding: 0 1.5em;
    text-decoration: none;
}
#coolMenu ul {
    position: absolute;
    display: none;
z-index: 999;
}
#coolMenu ul li a {
    width: 80px;
}
#coolMenu li:hover ul {
    display: block;
}
  • I decided to float the whole menu to contain it but you can use overflow hidden or even set a fixed width for the same purpose.
  • It is important to float the list elements rather than the links.
  • The links should be displayed as blocks, otherwise, they won’t behave as expected.
  • Absolute position the submenu and hide it to remove it from the regular flow and make it invisible. Also, set a high z-index to prevent the submenu from showing behind other elements.
  • Set a height for the link elements and the line-height equal to the height to center the text vertically. By specifying a fixed height instead of just using padding you avoid flickering problems with jQuery animations later on.
  • Even though it’s not necessary to set a fixed width for the submenu items, it’s always a good practice. It allows you to style them more consistently later on.
  • Notice that the hover state is set on the list element and not the link.
With all this set, the menu should be already working. Try opening it in your browser and hovering over the third option to show the sub menu.

 

Improving Usability

 

This step will cover how to style the menu with some basic CSS to make it more accessible.
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
/* Main menu
------------------------------------------*/
#coolMenu {
    font-family: Arial;
    font-size: 12px;
    background: #2f8be8;
}
#coolMenu > li > a {
    color: #fff;
    font-weight: bold;
}
#coolMenu > li:hover > a {
    background: #f09d28;
    color: #000;
}
 
/* Submenu
------------------------------------------*/
#coolMenu ul {
    background: #f09d28;
}
#coolMenu ul li a {
    color: #000;
}
#coolMenu ul li:hover a {
    background: #ffc97c;
}
Keep in mind this is very basic, and is meant to be just an example. You can style this however you want. The important thing to remember here is, as I mentioned before that the hover states, are styled in the list items and not the links.

 

Thursday, May 10, 2012

Open Source Java GPS Map Application Framework

The dinopolis gpstool package is an open source (LGPL) Java GPS application. It consists of different modules that may be used as a programmer's framework or as an application. The main application is GPSylon. A smaller command line tool (demonstration of the gpsinput library) is named GPSTool. The library that is used to communicate with the gps device can be used independently and is provided as a separate jar file (since version 0.5).

Short Description of GPSylon

GPSylon is able to show maps downloaded from the expedia map servers. It may connect to a gps device and track your position on the maps. At the moment, it is able to read gpsdata in the NMEA standard from a serial gps device, a file or a gps daemon across a network.
The main feature is the display of various maps. GPSylon allows the user to navigate around like in a digital atlas. It shows maps of different scales, so missing maps of one scale do not result in a black screen, but show the next larger scale.
It allows the download of a single map or for a given location or for multiple maps in a given rectangular area from mapblast or expedia map servers. In the download mouse mode the user may choose a single map or by dragging a rectangle with the mouse, the user may choose to download maps for a larger area. This functionality allows the user to download maps in a given scale for a larger area. Please only download maps you need and be careful not to download thousands of maps, as the map providers will discontinue their service when it is misused!
It uses the open source library openmap for various cartographic things.

Features

The following features are implemented.
  • Display different maps from mapblast or expedia server (also for maps of different scale).
  • Display current position (gps position).
  • Read gps data from serial device, file, or gpsd (daemon).
  • Uses the following NMEA sentences: GLL, HDG, RMC, GGA, GSV, DBT, VTG, HTD.
  • Display a track from gps data.
  • Save the track.
  • Load a track created from GPSylon or from gpsdrive.
  • Import maps from gpsdrive.
  • Download a map for a given position.
  • Download maps for an area.
  • Measure distance (ruler).
  • Read and display shape files (very basic, not well tested!).
  • display graticule lines
  • window to display the raw nmea data
  • Location Marker support: (creating markers, load markers from files (comma or space separated (name, latitude, longitude [,category]) - in that order!)), export markers to csv files, icons for categories, import geonet data (available from http://164.214.2.59/gns/html/index.html)
  • Database support for Location Markers - selection of categories to display.
    Different databases are supported (derby and hsqldb (both pure java, zero configuration), mysql and postgresql) - the database and all tables are created automatically
  • Level Of Detail: depending on the chosen scale, not all location markers are displayed. The level of detail is increased when the user zooms in or chooses to override the level of detail. This behaviour might be tricky, when the user creates a location marker in a category that does not show due to its higher level of detail. So the user may not see the newly created marker.
  • Search for location markers and set the center of the map to a search result. This is extremely useful in combination with the geonet data. So, after importing the geonet data, one is able to search for very small villages or other points of interest. When using mysql or postgresql as a database, the lookup for names of location markers is very fast, the (default) hsql database is about 5 to 10 times slower (but also works perfectly, just slower :-). So if one or more geonet files should be imported, I recommend mysql or postgresql (see in the installation section for configuration details).

Supported GPS Devices

In general, all gps devices that support NMEA communication should work. Garmin protocol support is built in.
There were reports of the following devices to work with GPSylon:
  • Garmin Etrex Summit/Legend (NMEA/garmin modes) tested by myself)
  • Garmin eMap (NMEA/garmin modes) (reported by Thomas Müller))
  • Trimble Lassen SK8 (NMEA mode) (reported by Didier Donsez)
  • Garmin 35 (NMEA mode) (reported by Antonio)
  • Conexant '99 embedded module (NMEA mode) (reported by Antonio)
  • LeadTek Gps-9543 embedded module (NMEA mode) (reported by Antonio)
  • Garmin Geko 201 (garmin mode) (reported by Frank Wilhelm)
  • GlobalSat Bluetooth GPS BT-338 (tested by myself)
  • Navilock NL-303P PDA-GPS-Receiver with Serial/USB converter (tested by Silverbullet)
Linux users please note: serial ports must be like /dev/ttySXX, as otherwise rxtx does not recognize the port. So for bluetooth or USB devices, a symlink is needed!
For bluetooth connection, I used the following commands under linux to create a serial connection with bluetooth. First, find the id of your bluetooth device. I used hcitool for this:
            hcitool scan
            output:
            Scanning ...
            00:0B:5D:13:91:49       BEGRZ9001001
            00:0D:B5:30:3C:0A       BT-GPS-303C0A
            
The first id is my bluetooth dongle on the pc, the second is the gps device. So, with this id, we can create a virtual serial port using rfcomm:
            rfcomm bind /dev/ttyS50 00:0D:B5:30:3C:0A
            
As rxtx does not allow /dev/rfcomm0 as serial device, I used /dev/ttyS50 (all ttys below 50 were already existent in my installation). A symlink from ttyS50 to rfcomm0 also works! After this, I set some port parameter (I'm not sure, if this is really needed!):
            stty -F/dev/ttyS50 -raw -onlcr
            
Now, GPSTool or GPSylon can use the serial port /dev/ttyS50 for communication with the nmea bluetooth gps device. After closing the application, one should release the bluetooth serial port:
            rfcomm release /dev/ttyS50
            
Please note, that all these commands (except for the application start) need to be run as root!

Installation

No installation of GPSylon itself is needed. Nevertheless, some dependencies exist:
  • Java in Version 1.4 (or better) is needed. It can be obtained from Sun's Website. Development is currently done with version 1.5, but tests are done for version 1.4. Java version 1.3 will NOT work!
  • Starting from Gpsylon V0.5.2, NO installation of the Java serial libraries are needed anymore! The native libraries are shipped with Gpsylon and start scripts are provided (for Linux and Windows) for Gpsylon and Gpstool (ther command line application). So just unpack the archive, and run (or double click) gpsylon.cmd, gpstool.cmd (for Windows) respectivly gpsylon.sh, gpstool.sh for Unix (Native Libraries for Linux, Sun Solaris and MacOSX are provided). As there is no Apple computer around for testing, I am not sure, if the unix scripts will work. Feedback is welcome!
    Jan van Haarst reported that comfoolery can be used to forward the serial data to a network socket. GPSylon may connect to this socket when it is configured to use gpsd instead of the serial device.

Database for Location Markers

GPSylon is able to store and retrieve location markers from relational databases via JDBC. By default it uses the pure java open source Hypersonic DB (hsqldb). It has the advantage that no installation is needed and GPSylon creates a database on demand without any hassle.
As the geonet dataset is quite large (e.g. Austria 50 thousand entries, Germany 170 thousand entries), hsqldb seemed quite slow. So I gave it a try with mysql and it seems to be faster! Especially searching for location markers is faster by a factor 5 to 10! So I added a script that creates the table(s) needed (syntax differs slightly from the hsqldb syntax). The following steps are needed to use a mysql database instead of the built in hsqldb:
  • Install MySQL :-)
  • Create the database: e.g. with the command mysqladmin create gpsmap
  • Start GPSylon and edit database settings in the preferences (Location Marker tab):
    • JDBC Url: jdbc:mysql://localhost/gpsmap
    • JDBC Driver: com.mysql.jdbc.Driver
    • SQL Script to create the Database: sql/create_loation_mysql.sql
  • quit GPSylon
  • on the next start, GPSylon tries to access the new database, but cannot (as the tables are missing). It asks for administrators username/password (try "root" and empty password :-) so it can create the table(s). It will also add a user "sa" with no password for normal usage (access limited to gpsmap database).
  • That should be it! From now on, all location markers are stored and retrieved from the MySQL database.
For Postgresql support use the following configuration:
  • JDBC Url: jdbc:postgresql://localhost/gpsmap
  • JDBC Driver: org.postgresql.Driver
  • SQL Script to create the Database: sql/create_loation_postgresql.sql
The rest of the postgresql configuration is similar to the mysql configuration (install database, create a gpsmap database, create user and user rights, ...)

Run GPSylon

To start GPSylon, download the gpstool-archive, unpack it and call
java -jar gpssylon.jar
or if your environment is setup to handle jar-archives correctly, simply double click on the jar-archive (should work under windows). All needed classes are contained in the jar file. If you have the ant environment installed, call ant run.
For commandline arguments (everything may be configured in the application as well!), call
java -jar gpsylon.jar --help

Mouse Modes

GPSylon supports different mouse modes. Mouse modes may be added as plugins. At the moment, two mouse modes are available:
  • Navigation Mode: click anywhere in the map to zoom in and center at the clicked position. If the shift-key is held, a click zooms out. More navigational functionality will be implemented soon (pan, ...)
  • Download Mode: If the download mode is used, a window opens that displays some information about the map(s) to download. In the map window, a red rectangle (with crossed lines) shows the current location and size (size may not be exact and varies slightly from one internet map server to another). The user may change the location either by clicking in the map or by changing the coordinates in the download window. The coordinates may be entered in different formats (decimal, using the degree sign, etc.). The user may click and drag in the map to draw a rectangle. If the rectangle is larger that a single map, more than one rectangle is shown and the number of maps to download is shown in the download window. Please do not download maps excessively, as the companies that provide the maps do not like that and will stop their service if it is misused!

Plugins

GPSylon supports plugins of various kinds. The plugin-jars are used without the need to set the CLASSPATH. All jars in the directories [home]/.gpsylon/plugins and in the plugins directory of the applicaton are used.

Download

Please download the latest distribution of GPSylon at the download page on sourceforge.

Status

GPSylon is in beta-status. It runs quite stable, but many features are not implemented yet.

Articles about GPSylon

Elliotte Rusty Harold, the author of quite a few books about Java, mentioned GPSylon in his Cafe au Lait blog.

Other Projects

Other projects that use parts of the gpsinput/gpsylon code are:
  • GPS Position Producer
Projects that are somehow related to this project:
  • Gpsdrive was the main inspiration to write gpsylon.
  • MapGeneration tries to create free vector data from NMEA streams - this was one of the goals gpsylon was written for!
  • Maps4Free tries to do the same as a community project.

To Do List

urgent:
  • option to use always info from gpsdrive
  • optionally draw rectangle for small scale maps that do not show (done (map manager plugin)): done
  • download maps also larger than 1280x1024
  • use repaint(int,int,int,int): mostly done
  • are there GPS devices, that do not send RMC (for gps speed)??
  • check for speed sent from gps (calculation of distance s=v*t) (tachometer)
  • window showing NMEA data: done
Todo (wishlist):
routes
  • define route with mouse (like distant mouse mode)
  • name route
  • show table with available routes
  • download maps for a given route in a given scale (and image size)
  • follow a given route with gps
waypoints
  • different lists of waypoints: done, categories should do the job
  • display different list of waypoints: done, categories should do it
  • different symbols for waypoints: done, for a couple of categories, more to come
  • store waypoints in database (hsqldb, mysql): done
overlays
  • show major cities (CSV), use them as waypoints
  • shape files: done (experimental)
  • GML
location database (GNR)
  • search for name in GNR (zipped files) (done, when gnr is imported)
  • goto location (done)
GPS Device
  • upload/download waypoints
  • download Tracks: download is done
  • upload Tracks
gps tracking
  • pursuit mode: done, cdaller 2002/09/06
  • as soon as manual navigation on screen, disable pursuit mode.
  • different color for height or speed
  • save gps tracks: done
  • load gps tracks from gps device: done
  • load gps tracks from file: done for own tracks, track of gpdsrive and gml tracks
  • autoscale (set scale, depending on speed)
vectorize tracks
  • define nodes (crossings) and arcs between nodes
  • define type of arcs (highway, smaller road, bicycle path)
  • export as GML
  • import as GML
communication to other applications
  • import/export maps, tracks, waypoints to gpsdrive, gpspoint (partly done)
  • option to leave maps there or copy them to .gpsylon/maps directory
maps
  • import scanned maps
  • download from different servers (expedia, mapblast, ...): done
  • allow proxy authentication: done
  • show table of maps (allow to delete, rename?, ...): partly done
  • download an area of maps: done<
autoroute calculation
    need vector data for this!
speech
  • output
  • input
distance notification
  • provide notifications for specific points (e.g. radar warning)
context menus (right mouse) / one button mouse (touchscreen) support????
  • set position
  • set destination
  • set waypoint
  • let each layer add menu for this

Compile Source Distribution

To compile the source distribution, the java make tool Ant from the apache project is needed. When correctly installed, a ant compile should be enough to compile the source.
ant help gives all ant-tasks.

Commandline tool GPSTool

GPSTool is a small command line application that demonstrates the usage of the classes to read data from a gps device. The main class is org.dinopolis.gpstool.GPSTool and it may be started using the provided gpstool-<version>.jar file (execute in a command window java -jar gpsylon-<version>.jar - double click does not make much sense, as it is a commandline application). Use "--help" to see all commandline switches.
The following features are implemented in GPSTool:
  • Show current position/altitude/speed/heading/info about satellites.
  • Use NMEA or Garmin protocol.
  • Download tracks, routes, and/or waypoints and print them in GPX format.
  • Make screenshots from the display of the gps device. This is tested with the following models: Garmin eTrex Summit, eTrex Legend, eMap, Geko201, Streetpilot III (partly, needs more work - could not finish due to the device powered down after sending the 10th line of the image).
  • Supprts Velocity templates to print tracks, routes, waypoints. These templates are easy to write. Use command line switch " --printdefaulttemplate" to show the gpx template. Other templates are provided in the auxiliary directory. 

Link: http://www.tegmento.org/gpsylon/

Monday, May 7, 2012

Reading Google Map pointers from a MySQL database

This is what how you can plot points on a google map using the google maps API, combined with a MySQL database.
The basic premise is that you have a MySQL database containing a series of latitudes and longitudes, and you need to read the latitudes/longitudes from the database and plot them onto the google map.

First thing first, create a a simple database table with a column for both latitude and longitude, you would of course have other fields depending on what data you are using the google map to represent. For simplicities sake, I’ve called them ‘lat’ and ‘lon’:

CREATE TABLE `map` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`lat` DECIMAL( 10, 6 ) NOT NULL ,
`lon` DECIMAL( 10, 6 ) NOT NULL ) ENGINE = MYISAM

We have set the lat and long as DECIMAL(10,6) to enable us to use decimal points due to how lat/long is represented (i.e 52.132633 is a latitude). We’ve also thrown in a auto incrementing ID for the primary key.
Now we have the MySQL table, we need to populate it, so go ahead and throw some latitudes and longitudesinto it. If you are feeling adventurous you can take a stab at Geocoding some locations using the API (I will be covering Geocoding in another article shortly). You can grab some latitudes and longitudes using maporama to search for a location, and you will find the lat/long on the bottom left corner of your screen.

Now onwards with the code.

First we need to connect to the database:
 
mysql_select_db(“dbname”, $db); ?&gt;

Next, we will need to include the google maps API key in the headof your page.


So, in the header of your page, enter this bit of script, with your API key placed where it says so:

<script src=“http://maps.google.com/maps?file=api&amp;v=2&amp;key=ENTERYOURKEYHERE” type=“text/javascript”></script>

Now we have set up access to the DB and linked to our google maps API, we can continue with the creation of the map.

Still in the of the page, create some javascript that will create the points. In this instance we want the points clickable so when you click on the point on the map, it will go to another webpage. For this we use the GEvent.addListener function, which will direct the user to the new page when they click on the point. We are directing people to a PHP page that will take the point as a variable from the address bar (using GET) and then display some sort of information depending on what is required.

<script type=“text/javascript”>// <![CDATA[
        function createMarker(point,html) {         var marker = new GMarker(point);
       GEvent.addListener(marker,"click",function(){ top.location = "http://www.websiteaddress.com/page.php?point="+point });
       return marker;
      }
// ]]></script>
Now we need to initialize the map:

<script type=“text/javascript”>// <![CDATA[
         function initialize() {
        if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"),{ size: new GSize(580,400) } );
              map.removeMapType(G_HYBRID_MAP);
                map.setCenter(new GLatLng(-3.703250,40.416741,0), 1);
                var mapControl = new GMapTypeControl();
                map.addControl(mapControl);
                map.addControl(new GLargeMapControl());
 
This is only half the code, but I thought I'd halt there for a second and explain what's happening, We are creating a new map, and placing it in the DIV on our page called 'map_canvas'. We can specifiy the size of the map you want, and what type of map you want(i,e satellite, street,hybrid etc). The size is controlled by the 'size:' command, and the type of map by the 'map.removeMapType', which will remove any type of map button you don't want. You also set the the starting point of the map by using the 'map.setCenter' function.

You finally add the controls onto the map, i.e if you want the zoom, and the directional cursors for navigating.
After initializing the map, and in the same script and function (notice how the above piece of javascript isn't closed by a

// ]]> tag, and the function isn't closed either with curly bracket), we need to now plot our points onto the map from our MySQL table. To do this we use PHP to perform a query on the database and extract the lat and long, assign them to variables and output each one in the javascript as a point. Simple (err..)!
$result_map = mysql_query($exe_map, $db)or die(mysql_error());
while(list($lat,$long) = mysql_fetch_row($result_map)){ echo "n var point = new GLatLng(".$lat.",".$long.");n";
echo "var marker = createMarker(point,'');n";
echo "map.addOverlay(marker);n";
echo "n";
}
?&gt;
And don't forget to close the function,'if' statement and script:
}
}
This basically gets all latitudes and longitudes from the database, row by row, and creates a point on the map by assigning the lat/long variables to a javascript variable called 'point'. A google map marker called 'marker' is then created with the coordinates assigned to 'point'. Finally the marker is added to the map. This is repeated for all points in the database table.

And that's the hard part done. We have read out our points from the database and added them to the google map. All we need to do is create All we need to do is put the google map in the place on the page we said we would ("map_canvas"), and initialize the javascript when the page loads, otherwise the map won't show up.

Make sure your body tag has these javascript fucntions included:
 Link: http://www.1stwebdesigner.com/tutorials/interactive-travel-map-google-maps-api/

Sunday, May 6, 2012

BlueCove JSR-82 Emulator module

BlueCove JSR-82 Emulator module

bluecove-emu is additional module for BlueCove to simulate Bluetooth stack.
bluecove-emu is a pure Java implementation of JSR-82 without Bluetooth hardware. Fully tested using TCK JSR-82 TCK test results
bluecove-emu requires Java 5 Standard Edition and uses RMI for inter process communication.
N.B. This is experimental module and have no monitoring GUI. Another module bluecove-emu-gui is in developement. Help us make it .

Usage

Start local bluetooth air simulator server
java -cp bluecove-2.1.0.jar;bluecove-emu-2.1.0.jar com.intel.bluetooth.emu.EmuServer
Start jsr-82 application that connects to air simulator server
java -Dbluecove.stack=emulator -cp bluecove-2.1.0.jar;bluecove-emu-2.1.0.jar;yourApp.jar org.your.app.Main
Start MIDP jsr-82 application that connects to air simulator server
java -Dbluecove.stack=emulator -cp microemulator.jar;bluecove-2.1.0.jar;bluecove-emu-2.1.0.jar org.microemu.app.Main btApp.jad

Emulator in Unit tests

Emulator has been designed to be used during unit test to help in automation of tests for JSR-82 applications.
For unit tests air simulator server can be started as in process server. EmulatorTestsHelper.startInProcessServer()
Documentation for BlueCove API that enables the use of Multiple Adapters and Bluetooth Stacks in parallel in the same JVM can be found here .
Complete JUnit test example can be found here ExampleTest

Configuration options

System properties:
  • `bluecove.stack=emulator` force BlueCove to use Emulator instead of real Bluetooth stack
  • `bluecove.deviceID=1` bluecove supports multiple local devices, this will force it to select second one.
  • `bluecove.deviceAddress=btaddr` select local devices by Bluetooth address
  • `bluecove.emu.rmiRegistryHost=localhost` air simulator server can be on remote computer
  • `bluecove.emu.rmiRegistryPort=8090` air simulator server listen on different port. Use 0 on the client to enable in process server (no rmi)
  • `bluecove.emu.rmiRegistry=true` air simulator server and RMI registry can be started inside client JVM
Emulator Configuration properties:
This is the resource file 'bluecove.emulator.properties' loaded by air simulator server. Defines devices address and names assignment. It also can define LocalDevice properties returned to the client application.

 Link:  http://bluecove.org/bluecove-emu/

Thursday, May 3, 2012

Free Java ME GPS Tracking Software

FollowMe 1.2 - Free Java ME GPS Tracking Software

 FollowMe 1.2 Free Open Source GPS tracking software for MIDP 2.0+ phones

FollowMe is the new name for Silent Software's LocateMe, this small (45K) application requires a mobile phone with an integrated GPS or a separate Bluetooth GPS and will show you the direction to given locations ("targets") without maps, using a pulsing direction arrow. You can request the location of other FollowMe users by text message, send your own position, or just simply save locations ("targets") for directions back to them later. Targets can even later be imported into Google Earth or Maps.


The Features

  • "Target" other FollowMe users' positions via a text message
  • Save multiple locations (targets "waypoints") with names (NEW for 1.2)
  • Stores your targets as Google Earth/Maps KML (NEW for 1.2)
  • Send your current position to other FollowMe users via text message
  • Connects to any mobile phone integrated GPS or Bluetooth GPS
  • View all the satellites around you on a "radar" style view
  • Display RAW GPS data (suitable for testing)
  • Complete integrated GPS support (some features may not be available depending on phone GPS capability).

For developers the fully commented source code provides
  • Design patterns, i.e. lazy initialization, command, strategy patterns
  • An example of a 2 tier system
  • How to use PushRegistry and File Connector (JSR 118)
  • How to use the Record Store (JSR 118)
  • How to use Bluetooth (JSR 82)
  • How to use Text Messaging (JSR 120)
  • How to use the PIM (and hack to minimise the security notices - JSR 75)
  • How to use the Location Based API (JSR 179 - Nokia lapi.jar included for use on non GPS integrated phones)
  • How to use simple graphics (not using a Game Canvas however)
  • How to multi thread effectively
  • How to process raw NMEA GPS data
  • Basic usage of the NanoXML parser
  • Basic understanding of graphical and GPS trigonometry

 Known Issues
  • The application is not security signed (this costs money!), so you will be shown numerous security popups when you start it.
  • As your phone is not a compass the direction target arrow will only point to the correct direction once you start walking, and the phone can determine which way relative to North you are going, i.e. when you are stood still your phone doesn't know which direction you are facing! :) On startup, until the GPS gets an accurate fix, the direction arrow to the target WILL NOT BE SHOWN.
  • On first run there can be some delay discovering the Bluetooth devices in busy areas (i.e. it may display "Waiting for GPS..." on first run for some time). This is down to the Bluetooth device discovery picking up a large number of devices and querying them. Once you have located your GPS, future connections to the GPS do not require this discovery period and will be relatively quick.

Compatibility
This software has been tested on Nokia Series 40 3rd edition phones at a minimum resolution of 128x128 pixels and Sun WTK emulator at 240x320. It has also been successfully tested on a Nokia N95 and Nokia 6650 with integrated GPS', and the INQ1 phone with separate Bluetooth GPS.

Link: http://silentdevelopment.blogspot.com/