43 Replies Latest reply: Aug 30, 2010 12:29 PM by bloobi RSS

GPS location issue for Black Berry Application

Newbie

We have implemented GPS in our BlackBerry(BB) application to get the current location coordinates that we are using to get information like - location name, location zip code, etc.

 

 

 

To develop this, we followed the document provided by BlackBerry official website which is available right now at this location - http://docs.blackberry.com/en/developers/deliverables/11944/GPS_overview

_857606_11.jsp

 

 

 

It works fine when the device is in an area from where it can search satellites easily (say, outside a building and in an open space) but the problem starts when we use this inside a building and in this case, it is not able to fix the GPS and due to which we don't get location coordinates.

 

 

 

I have checked all the BlackBerry forums for this problem but I couldn't get any solution.

 

I have also increased the horizontal and vertical accuracy level to 2000 meters and with different Criteria for different modes other than a "null" Criteria but then also it didn't work.

 

 

 

Please check the different Criteria for different modes which I have

tested:

 

 

 

// CELLSITE

 

Criteria myCriteria = new Criteria();

 

myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);

myCriteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);

myCriteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);

myCriteria.setCostAllowed(true);

  

 

// ASSIST

Criteria myCriteria = new Criteria();

myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM);

myCriteria.setHorizontalAccuracy(500);

myCriteria.setVerticalAccuracy(500);

myCriteria.setCostAllowed(true);

  

 

// AUTONOMOUS

Criteria myCriteria = new Criteria();

myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);

myCriteria.setHorizontalAccuracy(2000);

myCriteria.setVerticalAccuracy(2000);

myCriteria.setCostAllowed(false);

  

 

//any of the available location providers will be returned if myCriteria is null

 

Criteria myCriteria = null;

 

 

 

My question is, how is GoogleMaps application able to find the locations by using GPS inside a building? Is there any way in which we can also get the location coordinates by using GPS when we're inside a building?

  • Re: GPS location issue for Black Berry Application
    peter_strange Master

    Google doesn't just use GPS.  Google also have GPS located all the cell towers and so can map from these to your approximate location.  So if you are on wireless, Google will have a good chance of figuring out approximately where you are.

     

    GPS on the other hand, has no chance. 

     

    There are Threads on this forum that talk about how one might use Google or another provider to find this out for yourself based on your current tower. Have a search around. 

  • Re: GPS location issue for Black Berry Application
    Newbie

    njnjnj,

     

    I've been suffering from the same problem the past week and I've finally reached a solution. I use google's geolocation web service to retrieve location using cell ids. Its not very accurate but workable.

     

    The webservice (http://www.google.com/loc/json) uses HTTP POST and takes a JSON string with the parameters required to triangulate the phone. To construct the JSON string you'll need the j2me version of the JSON library for java.

     

    The following code constructs the json string that is required by the webservice (jsonString is of type JSONObject)

     

    jsonString.put("version", "1.1.0");
    jsonString.put("host", "maps.google.com");
    int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
    jsonString.put("home_mobile_country_code", Integer.parseInt(Integer.toHexString(x)));
                    
    jsonString.put("home_mobile_network_code", RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));
    int radio = RadioInfo.getNetworkType();
                    
    jsonString.put("radio_type","gsm");
    jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
    jsonString.put("request_address", true);
    jsonString.put("address_language", "en_GB");
                    
    CellTower cellInfo = new CellTower(Integer.toHexString(x),                                                  GPRSInfo.getCellInfo().getLAC(),                                                   GPRSInfo.getCellInfo().getRSSI(), GPRSInfo.getCellInfo().getCellId(),                                                    0,RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));
    Hashtable map = new Hashtable();
    map.put("mobile_country_code",new Integer(Integer.parseInt(cellInfo.mobileCountryCode)));
    map.put("location_area_code", new Integer(cellInfo.locationAreaCode));
    map.put("signal_strength", new Integer(cellInfo.signalStrength));
    map.put("cell_id", new Integer(cellInfo.cellID));
    map.put("age", new Integer(0));
    map.put("mobile_network_code",new Integer(cellInfo.mobileNetworkCode));
                    
    JSONArray array = new JSONArray();
    array.put(0,map);
                    
    jsonString.put("cell_towers",array)

     

    CellTower is an inner class with the following structure

     

    private class CellTower{
            public String mobileCountryCode;
            public int locationAreaCode;
            public int signalStrength;
            public int cellID;
            public int age;
            public int mobileNetworkCode;
            
            private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc){
                mobileCountryCode = mcc;
                locationAreaCode = lac;
                signalStrength = ss;
                cellID = ci;
                age = a;
                mobileNetworkCode = mnc;
            }
        }

     

    Once you construct the JSON string above you just POST it to the webservice.

     

    To retrieve longitude and latitude from the response string simply parse it into a JSONObject using the following code:

     

    try{
                    JSONObject ob = new JSONObject(response);
                    JSONObject ob2 = (JSONObject) ob.get("location");
                    
                    Double longitude = (Double)ob2.get("longitude");
                    Double latitude = (Double)ob2.get("latitude");
                                   
                    application.geoLocatorFinished(longitude.doubleValue(),latitude.doubleValue());
                
                }catch(JSONException exp){
                    application.log("JSON String error "+response);
                }

     

    The application.geoLocatorFinished() method is what I used as a callback method to my controller object to proceed with processing the longitude and latitude.

     

    Well hope this helps you!

     

    If you need anything else please let me know!

     

    Good luck! 

    Nawara

    • Re: GPS location issue for Black Berry Application
      mohitsharma Novice

      hi nawara,

       

      Can u post a link for the specification of this Google Maps API?

       

       

      thanks.

      • Re: GPS location issue for Black Berry Application
        Newbie

        Hi mohitsharma,

         

        The specs could be found here http://code.google.com/p/gears/wiki/GeolocationAPI

        • Re: GPS location issue for Black Berry Application
          mohitsharma Novice

          hey,

           

          which JSON library you are usaing?

           

          thanks.

          • Re: GPS location issue for Black Berry Application
            Newbie

            Hi

             

            I'm using the json library available for j2me. It took me a while to find it and finally came across the source code.. I've uploaded a rar file containing the source code files to this link for you to download

             

            You can either include these source files in your project or create another project that has them and compile it as a Library. Let me know if you need any help using it

            • Re: GPS location issue for Black Berry Application
              mohitsharma Novice

              hey thanks.

              was looking for the same but couldn't find it.

              • Re: GPS location issue for Black Berry Application
                Newbie

                Anytime man..

                 

                Let me know how things go and if you need anymore help please tell me

                 

                Good luck

                • Re: GPS location issue for Black Berry Application
                  Newbie

                  works!

                   

                  Thanks alot for this thread

                    • Re: GPS location issue for Black Berry Application
                      Newbie

                      Hello, can someone kindly give us the code of how to post the JSON string to the google web service? Thanks a lotSmiley Happy

                      • Re: GPS location issue for Black Berry Application
                        Newbie

                        Hi Deadlysugarcan

                         

                        Source code to open an http connection and post the JSON string to google's service

                         

                        public static HttpConnection makeConnection(String url, byte[] postData) 
                            {
                                HttpConnection conn = null;
                                OutputStream out = null;
                                
                                try 
                                {
                                    conn = (HttpConnection) Connector.open(url)
                        
                                    conn.setRequestMethod(HttpConnection.POST);
                        
                                    conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
                                    conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,"application / requestJson");
                        
                                    out = conn.openOutputStream();
                                    out.write(postData);
                        
                                } 
                                catch (IOException e1) 
                                {
                                } 
                                finally 
                                {
                                    if (out != null) 
                                    {
                                        try 
                                        {
                                            out.close();
                                        } 
                                        catch (IOException e2) 
                                        {
                                        }
                                    }
                                }    
                                
                                return conn;
                            }

                         

                         

                        of course your postData byte array is the JSON string that you've created using the above code in this thread.

                         

                        Good luck!

                        • Re: GPS location issue for Black Berry Application
                          Newbie

                          Thank so muchSmiley Happy but I am really new to json. How can we pass JSONObject to the second parameter of public static HttpConnection makeConnection(String url, byte[] postData) ?

                          • Re: GPS location issue for Black Berry Application
                            Newbie
                            Try JsonObject.toString().getBytes(); This should give u the array u need to pass to the method
                            • Re: GPS location issue for Black Berry Application
                              Newbie

                              Finally got it done! Thanks a lotSmiley Happy So happy to see my 8520 with geolocation capability!

                               

                              I see that there is also WiFi data that can be used in this Google API, but when I construct the WiFi data, I cannot retrieve the MAC of my WiFi MAC add as well as its signal strength.

                               

                              Did you guys try that?

                              • Re: GPS location issue for Black Berry Application
                                rrey2279 Newbie

                                There were rumors floating around DevCon last year that Google is cancelling this service Q4 of 2010.

                                 

                                Be careful not to put your Location eggs all in 1 basket.

                                 

                                Just my .02 dollars.

                                 

                                Other cell ID options are opencellid.org and navizon.com (MexensLocationProvider)

                                • Re: GPS location issue for Black Berry Application
                                  bsmith138 Novice

                                  I'm just trying to implement this as well.  I'm assuming that once we send the data we have to use the same connection to read the data off it.

                                   

                                  I'm getting a NullPointerException for some reason it goes alright until: 

                                  int responseCode = httpConn.getResponseCode();

                                   

                                  this is my code:

                                   

                                   

                                  private String queryViaHttp(String url, byte[] postData) {
                                        String resultString = null;
                                        try {
                                           HttpConnection httpConn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
                                           httpConn.setRequestMethod(HttpConnection.POST);
                                           httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
                                           httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, "application / requestJson");
                                           OutputStream out = httpConn.openOutputStream();
                                           out.write(postData);
                                           if(out != null) {
                                              out.close();
                                           }
                                           int responseCode = httpConn.getResponseCode();
                                           if (responseCode == HttpConnection.HTTP_OK) {
                                              InputStream inputStream = httpConn.openInputStream();
                                              ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                              byte[] buffer = new byte[512];
                                              int len = 0, size = 0;
                                              while ((len = inputStream.read(buffer)) != -1) {
                                                 byteArrayOutputStream.write(buffer);
                                                 size += len;
                                              }
                                              byteArrayOutputStream.flush();
                                              resultString = byteArrayOutputStream.toString();
                                              byteArrayOutputStream.close();
                                              if (inputStream != null)
                                                 inputStream.close();
                                              if (httpConn != null)
                                                 httpConn.close();
                                           } // end-if
                                        } catch (IOException e) {
                                           return null;
                                        }
                                        return resultString;
                                     }

                                   

                                  Can someone tell me if I'm doing it right.  thanks.

                                • Re: GPS location issue for Black Berry Application
                                  Newbie

                                  Hi, I tried both Google's API and OpenCellID, I would say that the result from Google is rather accurate. As you mentioned we cannot reply on Google because of licence and other unexpected problems.

                                   

                                  Here is a bigger issue when we use OpenCellID. It returns the same Longitude/Latitude even if I go through many streets by metro in Paris.

                                   

                                  And I got the pair of longitude/ latitude which was obviously far from Paris!

                                   

                                  For exemple, I did't get the right position from this URL which I built:


                                  OpenCellID URL=http://www.opencellid.org/cell/get?key=mykey&mnc=1&mcc=208&lac=38662&cellid=16386

                                   

                                  Is there a way to improve the accuracy to get the good result like Google? 

                                   

                                   


                                   



                                  • Re: GPS location issue for Black Berry Application
                                    febiyan Newbie

                                    @DeadlySugarCan

                                     

                                    What do you mean by licence? Do we need to obtain a licence to use Google's API? Are there any restrictions in using the API?

                                    • Re: GPS location issue for Black Berry Application
                                      flybirdtt Novice

                                      Anyone can help me ? thanks

                                      i also use the code to get the coordiante for google geolocation,

                                      but it return the string is :"{}"

                                      Pls tell what wrong with this code

                                      package Util;
                                      
                                      import java.io.ByteArrayOutputStream;
                                      import java.io.DataInputStream;
                                      import java.io.DataOutputStream;
                                      import java.io.IOException;
                                      import java.util.Hashtable;
                                      
                                      import javax.microedition.io.Connector;
                                      import javax.microedition.io.HttpConnection;
                                      
                                      import org.json.me.JSONArray;
                                      import org.json.me.JSONException;
                                      import org.json.me.JSONObject;
                                      
                                      import net.rim.device.api.io.http.HttpProtocolConstants;
                                      import net.rim.device.api.servicebook.ServiceBook;
                                      import net.rim.device.api.servicebook.ServiceRecord;
                                      import net.rim.device.api.system.CoverageInfo;
                                      import net.rim.device.api.system.GPRSInfo;
                                      import net.rim.device.api.system.RadioInfo;
                                      import net.rim.device.api.system.WLANInfo;
                                      
                                      public class QuickLocating {
                                      
                                       public void locating() throws IOException{
                                        byte[] postData = setParemeter().toString().getBytes();
                                        JSONObject jsonObject = null;
                                        HttpConnection gpsConnection;
                                        DataOutputStream os;
                                        DataInputStream dis;
                                        String gpsString = retrunURLString("http://www.google.com/loc/json");
                                        try {
                                         gpsConnection = (HttpConnection) Connector.open(gpsString);
                                         gpsConnection.setRequestMethod(HttpConnection.POST);
                                         gpsConnection.setRequestProperty(
                                           HttpProtocolConstants.HEADER_CONTENT_LENGTH, String
                                             .valueOf(postData.length));
                                         gpsConnection.setRequestProperty(
                                           HttpProtocolConstants.HEADER_CONTENT_TYPE,
                                           "application / requestJson");
                                         os = gpsConnection.openDataOutputStream();
                                         os.write(postData);
                                         int rc = gpsConnection.getResponseCode();
                                         if (rc != HttpConnection.HTTP_OK) {
                                          return;
                                         }
                                         dis = gpsConnection.openDataInputStream();
                                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                         int j = 0;
                                         while ((j = dis.read()) != -1) {
                                          baos.write(j);
                                         }
                                         byte[] data = baos.toByteArray();
                                         String jsonString = new String(data);
                                         try {
                                          jsonObject = new JSONObject(jsonString);
                                         } catch (JSONException e) {
                                          e.printStackTrace();
                                         }
                                         JSONObject locationObject = jsonObject.getJSONObject("location");
                                         if (locationObject.getDouble("latitude") != 0.0
                                           && locationObject.getDouble("longitude") != 0.0) {
                                          Global.lat = locationObject.getDouble("latitude");
                                          Global.lng = locationObject.getDouble("longitude");
                                          Global.horizontal_accuracy = locationObject
                                            .getDouble("accuracy");
                                          Global.locAvailable = true;
                                         }
                                        } catch (JSONException e) {
                                         // TODO: handle exception
                                         e.printStackTrace();
                                        }
                                      
                                       }
                                      
                                       public JSONObject setParemeter() {
                                        JSONObject jsonString = new JSONObject();
                                      
                                        try {
                                         jsonString.put("version", "1.1.0");
                                         jsonString.put("host", "maps.google.com");
                                         int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
                                         jsonString.put("home_mobile_country_code", Integer.parseInt(Integer
                                           .toHexString(x)));
                                         jsonString.put("home_mobile_network_code", RadioInfo
                                           .getMNC(RadioInfo.getCurrentNetworkIndex()));
                                      
                                         int radio = RadioInfo.getNetworkType();
                                         if(radio==RadioInfo.NETWORK_CDMA){
                                          jsonString.put("radio_type", "cdma");
                                         }
                                         else{
                                          jsonString.put("radio_type", "gsm");
                                         }
                                         jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
                                         jsonString.put("request_address", true);
                                         jsonString.put("address_language", "en_GB");
                                      
                                         CellTower cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo
                                           .getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
                                           GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
                                             .getMNC(RadioInfo.getCurrentNetworkIndex()));
                                         Hashtable map = new Hashtable();
                                         map.put("mobile_country_code", new Integer(Integer
                                           .parseInt(cellInfo.mobileCountryCode)));
                                         map.put("location_area_code",
                                           new Integer(cellInfo.locationAreaCode));
                                         map.put("signal_strength", new Integer(cellInfo.signalStrength));
                                         map.put("cell_id", new Integer(cellInfo.cellID));
                                         map.put("age", new Integer(0));
                                         map.put("mobile_network_code", new Integer(
                                           cellInfo.mobileNetworkCode));
                                      
                                         JSONArray array = new JSONArray();
                                         array.put(0, map);
                                      
                                         jsonString.put("cell_towers", array);
                                        } catch (JSONException e) {
                                         // TODO Auto-generated catch block
                                         e.printStackTrace();
                                        }
                                        return jsonString;
                                       }
                                      
                                       public static String retrunURLString(String url) {
                                        String urlString = null;
                                        if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                                         // WIFI
                                         urlString = url + ";interface=wifi";
                                        } else {
                                         int coverageStatus = CoverageInfo.getCoverageStatus();
                                         ServiceRecord record = getWAP2ServiceRecord();
                                         if (record != null
                                           && (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
                                          // WAP 2.0
                                          urlString = url + ";deviceside=true;ConnectionUID="
                                            + record.getUid();
                                         } else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
                                          // BES/MDS
                                          urlString = url + ";deviceside=false";
                                         } else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
                                          // Direct TCP/IP
                                          urlString = url + ";deviceside=true";
                                         } else if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
                                          // BIS
                                          urlString = url + ";deviceside=false;ConnectionUID="
                                            + record.getUid();
                                         }
                                        }
                                        return urlString;
                                       }
                                      
                                       protected static ServiceRecord getWAP2ServiceRecord() {
                                        ServiceBook sb = ServiceBook.getSB();
                                        ServiceRecord[] records = sb.getRecords();
                                        for (int i = 0; i < records.length; i++) {
                                         String cid = records[i].getCid().toLowerCase();
                                         String uid = records[i].getUid().toLowerCase();
                                         if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
                                           && uid.indexOf("mms") == -1) {
                                          return records[i];
                                         }
                                        }
                                        return null;
                                       }
                                      
                                       private class CellTower {
                                        public String mobileCountryCode;
                                        public int locationAreaCode;
                                        public int signalStrength;
                                        public int cellID;
                                        public int age;
                                        public int mobileNetworkCode;
                                      
                                        private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc) {
                                         mobileCountryCode = mcc;
                                         locationAreaCode = lac;
                                         signalStrength = ss;
                                         cellID = ci;
                                         age = a;
                                         mobileNetworkCode = mnc;
                                        }
                                       }
                                      }
                                      
                                      • Re: GPS location issue for Black Berry Application
                                        Newbie

                                        Maybe it's  because if the network is CDMA and you use GPRSInfo.getCellInfo.getCellID() ,GPRSInfo.getCellInfo().getLAC() ,and GPRSInfo.getCellInfo().getRSSI() you do not get any valid data.

                                        You should instead try CDMAInfo.getCellInfo().getBID(), CDMAInfo.getCellInfo().getNID() and RadioInfo.getSignalLevel()

                                        • Re: GPS location issue for Black Berry Application
                                          flybirdtt Novice

                                          Thanks.

                                          But the network is GSM. i tested.

                                          I tested it in singapore. 

                                          I don't know why this api  return "{}"

                                          Just a null

                                          • Re: GPS location issue for Black Berry Application
                                            flybirdtt Novice

                                            Any help?

                                            Who will test this code for me?

                                            Cause i can not find the wrong code inside.

                                            • Re: GPS location issue for Black Berry Application
                                              Novice

                                              I guess you are creating the JSONObject using this line from your code:

                                               

                                               

                                               

                                              JSONArray array = new JSONArray();
                                                 array.put(0, map);
                                              

                                              and then returning

                                               

                                              jsonString.put("cell_towers", array);
                                              

                                               

                                               

                                               

                                              If thats the case an array is an array and a string is a string, you need to convert your array into a string, try using(I did not test your code):

                                               

                                              jsonString.put("cell_towers", array.toString());
                                              
                                              • Re: GPS location issue for Black Berry Application
                                                flybirdtt Novice

                                                Thanks. But i do think we can do this.

                                                if you set  data like this: jsonString.put("cell_towers", array.toString());

                                                 

                                                this data formate like:  "cell_towers": "[{.......}]"

                                                the "cell_towers" tag is a string not a  arrary.

                                                • Re: GPS location issue for Black Berry Application
                                                  flybirdtt Novice

                                                  i changed the map to jsonobject

                                                  JSONObject map = new JSONObject();

                                                  It  return the data.but only one time. 

                                                  It also return the null after this time.

                                                  So i think this code is corret.

                                                  the null data  means : the location was not successfully resolved some time.

                                                  I find this description from google:

                                                   

                                                  If the request format is invalid, the server responds with HTTP status 400. The details of the error should be plain text in the response.

                                                   

                                                  If the request format is valid, the server replies with HTTP status 200. If the location was successfully resolved, the location object is populated with the details. Otherwise, it is null. 

                                          • Re: GPS location issue for Black Berry Application
                                            rileygb Apprentice

                                            flybirdtt wrote:

                                            Thanks.

                                            But the network is GSM. i tested.

                                            I tested it in singapore. 

                                            I don't know why this api  return "{}"

                                            Just a null


                                            I've got your code working for GSM, still working for CDMA, but here's what I've got so far.

                                             

                                            Use this for setParemeter() 

                                             

                                            public String setParemeter() {
                                              int mobileCountryCode = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
                                              int radio = RadioInfo.getNetworkType();
                                              String radioType = null;
                                              
                                              
                                              if(radio == RadioInfo.NETWORK_GPRS)
                                                   radioType = "gsm";
                                              else if(radio == RadioInfo.NETWORK_UMTS)
                                                   radioType = "gsm";
                                                              
                                                              if(isBandSupported(RadioInfo.BAND_GSM_1800)||isBandSupported(RadioInfo.BAND_GSM_900)){
                                                    radioType = "gsm";
                                              }
                                              else if(isBandSupported(RadioInfo.BAND_UMTS_2100)){
                                                    radioType = "wcdma";
                                              }
                                                              
                                                              
                                              if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_EDGE)>0){
                                                   radioType = "gsm";
                                              }
                                              else if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_UMTS)>0){
                                                   radioType = "wcdma";
                                              }
                                              else
                                                    radioType = "gsm";  
                                              
                                              if(radio==RadioInfo.NETWORK_CDMA){
                                               radioType = "cmda";
                                              }
                                              
                                              CellTower cellInfo = null;
                                              
                                              if(radioType.equals("gsm")){
                                               cellInfo = new CellTower(Integer.toHexString(mobileCountryCode), GPRSInfo
                                                 .getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
                                                 GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
                                                  .getMNC(RadioInfo.getCurrentNetworkIndex()));
                                              }
                                              else if(radioType.equals("cmda")){
                                               cellInfo = new CellTower(Integer.toHexString(mobileCountryCode), CDMAInfo.getCellInfo()
                                                 .getNID(), RadioInfo.getSignalLevel(),
                                                 CDMAInfo.getCellInfo().getBID(), 0, CDMAInfo.getCurrentSID());
                                              }
                                              else{
                                                  String cellID = Integer.toHexString(GPRSInfo.getCellInfo().getBSIC());
                                                  cellID += (Integer.toHexString(GPRSInfo.getCellInfo().getCellId()));
                                                  cellInfo = new CellTower(Integer.toHexString(mobileCountryCode),GPRSInfo.getCellInfo().getLAC(),
                                                                                              GPRSInfo.getCellInfo().getRSSI(),Integer.parseInt(cellID,16),
                                                                                              0,RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));
                                              }
                                              
                                              String json = "";
                                              json += "{\"host\":\"maps.google.com\",";
                                              json += "\"address_language\":\"en_GB\",";
                                              json += "\"request_address\":true,";
                                              json += "\"carrier\":\"" + RadioInfo.getCurrentNetworkName() +"\",";
                                              json += "\"home_mobile_country_code\":" + Integer.parseInt(Integer.toHexString(mobileCountryCode)) + ",";
                                              json += "\"cell_towers\":";
                                              json += "[{\"signal_strength\":" + new Integer(cellInfo.signalStrength) + ",";
                                              json += "\"cell_id\":" + new Integer(cellInfo.cellID) + ",";
                                              json += "\"mobile_network_code\":" + new Integer(cellInfo.mobileNetworkCode) + ",";
                                              json += "\"location_area_code\":" + new Integer(cellInfo.locationAreaCode) + ",";
                                              json += "\"mobile_country_code\":" + new Integer(Integer.parseInt(cellInfo.mobileCountryCode)) + ",";
                                              json += "\"age\":0}],";
                                              json += "\"version\":\"1.1.0\",";
                                              json += "\"radio_type\":\"" + radioType + "\",";
                                              json += "\"home_mobile_network_code\":" + cellInfo.mobileNetworkCode + "}";
                                              
                                              sendString.setText(json);
                                              
                                              return json;
                                             }

                                             

                                            and change 

                                             

                                            byte[] postData = setParemeter().toString().getBytes();
                                            

                                             in locating() to 

                                             

                                            byte[] postData = setParemeter().getBytes();

                                             

                                            Cheers.

                                      • Re: GPS location issue for Black Berry Application
                                        Newbie
                                        Hi All, Has anyone tested that this code works on CDMA networks ? In some other thread I read it is mentioned that this won't work on CDMA devices.. IS IT THE CASE ?
                  • Re: GPS location issue for Black Berry Application
                    Newbie

                    First off, thank u very much for this post, works great!!!

                     

                    However a couple question comes to mind:

                     

                    When u add "host":"maps.google.com" to the request POST, aren't you saying that the request its coming form Google Maps?? If so, why?? Are there license problems using this API??

                     

                    And also I read that this API is Deprecated, does anyone know when will it stop working all together??


                    Thanks

                     

                    ANF3R

            • Re: GPS location issue for Black Berry Application
              Newbie

              Hi!

               

              Has been quite long time since you posted this article, but, I am having a lot of problems with the JSON library, and I saw that you already posted the solution, but actually the link has been finished, so I hope that you can post again this library.

               

              Thanks a lot!

            • Re: GPS location issue for Black Berry Application
              Newbie

              Anawara can you upload again the example of geolocation with cell tower position?

               

              The link is broken.,

               

              Regards!

              • Re: GPS location issue for Black Berry Application
                Newbie

                Hi all,

                 

                I've uploaded a while back an example that showed how to construct a JSON string for google's webservice. However, I noticed strange behavior when the phone was connected to a 3G network. Apparently the documentation of the 4.6 API is not complete. Here's the deal:

                 

                • if you're connected to a GPRS/EDGE/2G network then your cell id can be obtained through GPRSInfo.getCellInfo().getCellId()
                • if you're connected to UMTS/3G then your cell id is obtained through the following piece of code:
                String cellID = Integer.toHexString(GPRSInfo.getCellInfo().getBSIC());
                cellID += (Integer.toHexString(GPRSInfo.getCellInfo().getCellId()));
                int cell = Integer.parseInt(cellID,16);

                 

                 

                The reason is with UMTS the cell id is actually a result of the concatenation of the Base Station Identification Code and the cell Id in hexadecimal format converted back to decimal.

                 

                To properly determine whether you're connected to 3G or 2G use the following code:

                 

                if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_EDGE)>0){
                    radioType = "gsm";
                }
                else if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_UMTS)>0){
                    radioType = "wcdma";
                }

                 

                 

                I check the radioType string for "gsm" to determine how to calculate the cell id before proceeding.

                 

                code that generates JSON string changes to (all the rest remains the same):

                 

                 

                jsonString.put("version", "1.1.0");
                jsonString.put("host", "maps.google.com");
                int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
                                
                jsonString.put("home_mobile_country_code",                                  Integer.parseInt(Integer.toHexString(x)));
                jsonString.put("home_mobile_network_code", RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));
                                
                int radio = RadioInfo.getNetworkType();
                String radioType = null;
                                
                if(radio == RadioInfo.NETWORK_GPRS)
                     radioType = "gsm";
                else if(radio == RadioInfo.NETWORK_UMTS)
                     radioType = "gsm";
                                
                                if(isBandSupported(RadioInfo.BAND_GSM_1800)||isBandSupported(RadioInfo.BAND_GSM_900)){
                      radioType = "gsm";
                }
                else if(isBandSupported(RadioInfo.BAND_UMTS_2100)){
                      radioType = "wcdma";
                }
                                
                                
                if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_EDGE)>0){
                     radioType = "gsm";
                }
                else if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_UMTS)>0){
                     radioType = "wcdma";
                }
                else
                      radioType = "gsm";
                                
                jsonString.put("radio_type",radioType);
                jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
                jsonString.put("request_address", true);
                jsonString.put("address_language", "en_GB");
                                
                CellTower cellInfo = null;
                if(radioType.equals("gsm")){
                      cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo.getCellInfo().getLAC(),
                                                               GPRSInfo.getCellInfo().getRSSI(), GPRSInfo.getCellInfo().getCellId(),
                                                                0,RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));
                }
                else{
                    String cellID = Integer.toHexString(GPRSInfo.getCellInfo().getBSIC());
                    cellID += (Integer.toHexString(GPRSInfo.getCellInfo().getCellId()));
                    cellInfo = new CellTower(Integer.toHexString(x),GPRSInfo.getCellInfo().getLAC(),
                                                                GPRSInfo.getCellInfo().getRSSI(),Integer.parseInt(cellID,16),
                                                                0,RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));
                }
                Hashtable map = new Hashtable();
                map.put("mobile_country_code",new Integer(Integer.parseInt(cellInfo.mobileCountryCode)));
                map.put("location_area_code", new Integer(cellInfo.locationAreaCode));
                map.put("signal_strength", new Integer(cellInfo.signalStrength));
                map.put("cell_id", new Integer(cellInfo.cellID));
                map.put("age", new Integer(0));
                map.put("mobile_network_code",new Integer(cellInfo.mobileNetworkCode));
                                
                JSONArray array = new JSONArray();
                array.put(0,map);
                                
                jsonString.put("cell_towers",array);
                • Re: GPS location issue for Black Berry Application
                  cjlopez Newbie

                  Is there a way to get a better accuracy???

                   

                  I'm getting a 1491 accuracy and that.... kinda not really helpfull to what i want to achieve using this

                   

                  I'm trying to get to get the position of the 8520 we have around i'm trying to use this, but still, its not that helpfull with such accuracy, so, any way to improve accuracy

                   

                  This is the parameters i send the webservice

                   

                  {"host":"maps.google.com","address_language":"en_GB","request_address":true,"carrier":"TELCEL GSM","home_mobile_country_code":334,"cell_towers":[{"signal_strength":-82,"cell_id":32702,"mobile_network_code":32,"location_area_code":5031,"mobile_country_code":334,"age":0}],"version":"1.1.0","radio_type":"gprs","home_mobile_network_code":32}

                  And this is the response

                   

                  {"location":{"latitude":29.073722,"longitude":-110.936176,"accuracy":1491.0},"access_token":"2:a1dkNq9nfE0W8YpS:5kbhxJR_FPAAJOLf"}

                   

                  With the google maps app i get a pretty close localization, with with my code, i aint getting not even a slightly good one

                • Re: GPS location issue for Black Berry Application
                  Newbie

                  Hi Anwara,

                   

                  Thanks for the below posts. As I am new to JSON, I may have not understood it correctly. I get the below error while running the following:

                   

                  json.JSONException: JSONObject["location"] not found.

                  No stack trace

                   

                  The response that I get back in bytes is : [B@3b3a2da4

                   

                   The Code is as follows:

                   

                   public void run(){   

                      try{

                                  byte[] postData = setParameter();

                                  JSONObject jsonObject = null;

                                  HttpConnection gpsConnection;

                                  DataOutputStream os;

                                  DataInputStream dis; 

                                String gpsString = "http://www.google.com/loc/json"+";deviceside=true"; 

                                gpsConnection = (HttpConnection) Connector.open(gpsString);               gpsConnection.setRequestMethod(HttpConnection.POST);               gpsConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,String.valueOf(postData.length));           gpsConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,"application / requestJson");

                                  os = gpsConnection.openDataOutputStream(); 

                                os.write(postData);    

                                  int rc = gpsConnection.getResponseCode();

                                  if (rc != HttpConnection.HTTP_OK) { 

                                   System.out.println("oopsie Daisy"); 

                                   longitude = new Double(0); 

                                   latitude = new Double(0);

                                  }else{

                                      System.out.println("Response Code is " + rc); 

                                    dis = gpsConnection.openDataInputStream();

                                      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

                                    int j = 0; 

                                    while ((j = dis.read()) != -1) { 

                                       baos.write(j); 

                                       System.out.println(j); 

                                    byte[] data = baos.toByteArray(); 

                  System.out.println(data);

                                      String jsonString = new String(data);

                                       try {   

                                        jsonObject = new JSONObject(jsonString); 

                                          System.out.println(" I created new JSON Object"); 

                                    } catch (JSONException e) {   

                                      System.out.println(e);   

                                       e.printStackTrace();       

                              }                   

                  JSONObject locationObject = (JSONObject)jsonObject.get("location");

                                    if (locationObject.getDouble("latitude") != 0.0&& locationObject.getDouble("longitude") != 0.0) {   

                                       latitude= new Double(locationObject.getDouble("latitude"));

                                           longitude= new Double(locationObject.getDouble("longitude")); 

                                    }else{

                                          System.out.println("Cant get latitude and longitude");     

                                    longitude = new Double(0); 

                                        latitude = new Double(0); 

                                    } 

                               }// end of status == ok

                       }catch (JSONException e) { 

                            // TODO: handle exception 

                            System.out.println(e);

                              e.printStackTrace();

                          }catch(Exception e){ 

                            System.out.println(e); 

                            System.out.println(" i am in caught exception"); 

                            longitude = new Double(0); 

                            latitude = new Double(0); 

                            Launch.selectedLocality = "All";

                            Launch.selectedRegion = "All";

                          }finally{        } 

                       }          

                   

                        public byte[] setParameter() {

                        JSONObject jsonString = new JSONObject();
                        try {

                            jsonString.put("version", "1.1.0"); 

                            jsonString.put("host", "maps.google.com");

                              int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());

                                System.out.println(x); 

                              System.out.println(Integer.parseInt(Integer.toHexString(x), 16));

                                jsonString.put("home_mobile_country_code",Integer.parseInt(Integer.toHexString(x), 16));           System.out.println(RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));           jsonString.put("home_mobile_network_code", RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));                     int radio = RadioInfo.getNetworkType(); 

                           String radioType = null;   

                                   if(radio == RadioInfo.NETWORK_GPRS) 

                                radioType = "gsm";     

                        else if(radio == RadioInfo.NETWORK_UMTS)   

                              radioType = "gsm";          if(isBandSupported(RadioInfo.BAND_GSM_1800)||isBandSupported(RadioInfo.BAND_GSM_900)){               radioType = "gsm";            }

                  else if(isBandSupported(RadioInfo.BAND_UMTS_2100)){                radioType = "wcdma";            }

                                if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_EDGE)>0){

                                  radioType = "gsm";            }

                              else if((RadioInfo.getNetworkService() & RadioInfo.NETWORK_SERVICE_UMTS)>0){

                                  radioType = "wcdma";            } 

                            else                radioType = "gsm";

                                     jsonString.put("radio_type",radioType);

                              jsonString.put("carrier", RadioInfo.getCurrentNetworkName());

                              jsonString.put("request_address", true);

                              jsonString.put("address_language", "en_GB"); 

                                  CellTower cellInfo = null; 

                            if(radioType.equals("gsm")){ 

                                cellInfo = new CellTower(Integer.toHexString(x),GPRSInfo.getCellInfo().getLAC(),GPRSInfo.getCellInfo().getRSSI(),GPRSInfo.getCellInfo().getCellId(),0,RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));            }

                  else{                String cellID = Integer.toHexString(GPRSInfo.getCellInfo().getBSIC());   

                              cellID += (Integer.toHexString(GPRSInfo.getCellInfo().getCellId()));                cellInfo = new CellTower(Integer.toHexString(x),GPRSInfo.getCellInfo().getLAC(),GPRSInfo.getCellInfo().getRSSI(),Integer.parseInt(cellID,16),0,RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex()));            }       

                      Hashtable map = new Hashtable();

                              map.put("mobile_country_code",new Integer(Integer.parseInt(cellInfo.mobileCountryCode, 16))); 

                            map.put("location_area_code", new Integer(cellInfo.locationAreaCode));   

                          map.put("signal_strength", new Integer(cellInfo.signalStrength)); 

                            map.put("cell_id", new Integer(cellInfo.cellID));

                              map.put("age", new Integer(0));

                              map.put("mobile_network_code",new Integer(cellInfo.mobileNetworkCode));                                       JSONArray array = new JSONArray();

                              array.put(0,map);

                                jsonString.put("cell_towers",array);       

                  } catch (JSONException e) {   

                          // TODO Auto-generated catch block   

                          e.printStackTrace();               

                     } 

                     return jsonString.toString().getBytes();

                    }     

                   

                  //Cell Tower Class is exactly the same

    • Re: GPS location issue for Black Berry Application
      Newbie

      Hello anawara,

       

      Does the response is to be taken in below manner which we normally use to get the response ?

       

       InputStream _inputStream = null;
                   _inputStream = conn.openInputStream();
                   
                   // Get the ContentType
                   String type = conn.getType();
                  
                   // Get the length and process the data
                   int len = (int)conn.getLength();
                   if (len > 0)
                   {
                          int actual = 0;
                          int bytesread = 0 ;
                          byte[] data = new byte[len];
                          while ((bytesread != len) && (actual != -1))
                          {
                              actual = _inputStream.read(data, bytesread, len - bytesread);
                              bytesread += actual;
                          }
                       
                          String response= new String( data,0,bytesread);

  • Re: GPS location issue for Black Berry Application
    bloobi Newbie

    Hi,

    Here is a working code sample from http://www.anddev.org/poor_mans_gps_-_celltowerid_-_location_area_code_-lookup-t257.html and it don't use JSON libraries!.

     

     

      //Source : http://www.anddev.org/poor_mans_gps_-_celltowerid_-_location_area_code_-lookup-t257.html
                String requestUrl = "http://www.google.com/glm/mmap";
    
    
                ByteArrayOutputStream bOutArray = new ByteArrayOutputStream(); 
                DataOutputStream dos = new DataOutputStream(bOutArray); 
                dos.writeShort(21);
                dos.writeLong(0);
                dos.writeUTF("fr");
                dos.writeUTF("Sony_Ericsson-K750");
                dos.writeUTF("1.3.1");
                dos.writeUTF("Web");
                dos.writeByte(27);
                dos.writeInt(0);
                dos.writeInt(0);
                dos.writeInt(3);
                dos.writeUTF("");
                dos.writeInt(pCellId); // CELL-ID
                dos.writeInt(pLocationAreaCode); // LAC
                dos.writeInt(0);
                dos.writeInt(0);
                dos.writeInt(0);
                dos.writeInt(0);
                dos.flush();   
                dos.close();
    
    
               
                byte[] result = executeGmapRequest(dos);
                ByteArrayInputStream bInArray = new ByteArrayInputStream(result);
    
                DataInputStream dis = new DataInputStream(bInArray);
    
                dis.readShort();
                dis.readByte();
    
                int errorCode = dis.readInt();
    
                if (errorCode == 0) {
    
                    double lat = (double) dis.readInt() / 1000000D;
                    double lng = (double) dis.readInt() / 1000000D;
    
                    // Read the rest of the data
    
                    dis.readInt();
                    dis.readInt();
                    dis.readUTF();
    
                    //    byte[] ps = new byte[response.length];
                    System.out.println("GoogleMaps response : ");
    
                    return new GPSPosition(lat, lng);
    
                }
    
    
    
    

     

     

        String requestUrl = "http://www.google.com/glm/mmap";
                //String requestUrl = "http://www.google.com/glm/mmap";
                System.out.println("GoogleMaps request : " + requestUrl);


            /*    HttpConnection connection = null;
                DataInputStream input = null;
                DataOutputStream output = null;
                connection = (HttpConnection) Connector.open(requestUrl,Connector.READ_WRITE,true);
                connection.setRequestMethod(HttpConnection.POST);

                connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, "application/binary");

                output = new DataOutputStream(connection.openDataOutputStream());
                //output.write(pd);
    */
                //Source : http://www.anddev.org/poor_mans_gps_-_celltowerid_-_location_area_code_-lookup-t257.html

                ByteArrayOutputStream bOutArray = new ByteArrayOutputStream();  
                DataOutputStream dos = new DataOutputStream(bOutArray);  
                dos.writeShort(21);
                dos.writeLong(0);
                dos.writeUTF("fr");
                dos.writeUTF("Sony_Ericsson-K750");
                dos.writeUTF("1.3.1");
                dos.writeUTF("Web");
                dos.writeByte(27);
                dos.writeInt(0);
                dos.writeInt(0);
                dos.writeInt(3);
                dos.writeUTF("");
                dos.writeInt(pCellId); // CELL-ID
                dos.writeInt(pLocationAreaCode); // LAC
                dos.writeInt(0);
                dos.writeInt(0);
                dos.writeInt(0);
                dos.writeInt(0);
                dos.flush();    
                dos.close();