I have used the code below to get latitude and longitude in C#.Net. But in some cases it provides the wrong latitude/longitude. For example, if I search "Braås skola Växjö Sweden" it provides [56.879004,14.805852] which is Växjö's latitude/longitude not what we searched! So how do we resolve this problem to get the exact latitude/longitude. This problem happens in many cases like "Braås förskola 44:an VÄXJÖ", "Björkens förskola VÄXJÖ".
private const String _googleUri = "http://maps.google.com/maps/geo?q=";
private const String _googleKey = "yourkey";
private const String _outputType = "csv";
private static Uri GetGeocodeUri(String address) {
address = HttpUtility.UrlEncode(address);
return new Uri(String.Format("{0}{1}&output={2}&key={3}", _googleUri,
address, _outputType, _googleKey));
}
public static Coordinate GetCoordinates(String address) {
WebClient client = new WebClient();
Uri uri = GetGeocodeUri(address);
String[] geocodeInfo = client.DownloadString(uri).Split(',');
return new Coordinate(Convert.ToDecimal(geocodeInfo[2]), Convert.ToDecimal(geocodeInfo[3]));
}
Please help me get a better solution.
Request the places-service instead of geocoding.
Related
Is there any way to set the Metadata Description?
https://developer.android.com/reference/com/google/android/gms/drive/Metadata.html#getDescription()
If so, what is the length limit?
I can't see anything in the api: https://developer.android.com/reference/com/google/android/gms/drive/MetadataChangeSet.Builder.html
Unfortunately not at the moment, AFAIK. What I do right now is initializing both GDAA and RESTful API (see the 'trash solution' SO 22295903) like this:
private GoogleApiClient _gac;
private com.google.api.services.drive.Drive _svc;
public GoogleApiClient init(String email){
_gac = new GoogleApiClient.Builder(UT.ACTX).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName(email).build();
com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential crd =
GoogleAccountCredential.usingOAuth2(UT.ACTX,
Arrays.asList(com.google.api.services.drive.DriveScopes.DRIVE_FILE));
crd.setSelectedAccountName(email);
_svc = new com.google.api.services.drive.Drive.Builder(
AndroidHttp.newCompatibleTransport(), new GsonFactory(), crd).build();
return this;
}
You get the description from DGAA (GoogleApiClient _gac above), but update/write it to RESTFul like this (off UI thread):
public void oldDescUpW(String titl, String mime, String desc) {
try {
final FileList gLst = _svc.files().list()
.setQ("title = '"+titl+".jpg' and mimeType = '"+mime+"' and trashed = false")
.setFields("items(id)").execute();
if (gLst.getItems().size() == 1) {
final String sId = gLst.getItems().get(0).getId();
com.google.api.services.drive.model.File body =
new com.google.api.services.drive.model.File();
body.setDescription(desc);
_svc.files().patch(sId, body).execute();
}
} catch (Exception e) {}
}
It is also possible to use 'resource ID' from GDAA to address the file in RESTful, but it is not always immediately available (if the file is created in GDAA). See SO 22874657
DISCLAIMER:
It is a HACK and should not stay alive past GDAA delivery of an alternative.
Can I turn data contract attributes off and on dynamically? Essentially, I'd like two data contracts, one between the 3rd party and my app, and one between my app and my client - without having to manage two DTO classes. For example, consider MyDTO:
[DataContract]
public class MyDTO
{
[DataMember(Name = "Lame/3rdParty/Inbound/Key")]
public string MyCoolOutboundKey { get; set; }
}
I'd like to deserialize the DTO with ServiceStack.Text:
MyDTO dto = "{\"Lame/3rdParty/Inbound/Key\":\"CoolValue\"}".FromJson<MyDTO>();
But, I'd like to serialize it so that this Assertion would be true:
Assert.AreEqual("{\"MyCoolOutboundKey\":\"CoolValue\"}",dto.ToJson());
The actual object in question has over hundred properties, so I'm hoping to avoid having to create a second class just to allow for outbound serialization.
So, there is nothing wrong with your approach, but I think you are underestimating the power of JsonObject, it's kinda like LINQ to JSON.
I used it to get geo data from Google Maps and map it to a nice little DTO:
var jsonObj = jsonFromGoogleMaps.FromJson<JsonObject>();
return (
from x in jsonObject.Get<JsonArrayObjects>("results")
let geo = x.Get("geometry")
let loc = geo.Get("location")
return new Coords
{
Lat = x.Get<decimal>("lat"),
Lng = x.Get<decimal>("lng"),
}
).FirstOrDefault();
OK - it's pretty well established that you cannot change attributes at runtime.
An alternative that would create an end-run around the entire issue, would be to pre-process the incoming json, replacing the keys according to a map, i.e.:
Dictionary<String,String> map = new Dictionary<String,String>();
map.Add("Lame/3rdParty/Inbound/Key","MyCoolOutboundKey");
JsonObject result = new JsonObject();
JsonObject obj = jsonObject.Parse("{\"Lame/3rdParty/Inbound/Key\":\"CoolValue\"}");
foreach (var entry in obj)
{
entry.Key = map[entry.Key];
result[entry.Key] = entry.Value;
}
Assert.AreEqual("{\"MyCoolOutboundKey\":\"CoolValue\"}",result.ToJson());
This way the only data contract I'd require would be the one between my app and my app's clients.
I need search functionality like this site. But I am wondering how can I get coordinates from google api by street name?
Google Geocoding API
You can enter in an address and it will return the Lat/long co-ordinates in a Json response or XML etc
You can read about it here:
http://code.google.com/apis/maps/documentation/geocoding/
In the onclick event of search write
List<Address> addresses = geoCoder.getFromLocationName("enter location name",5);
p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = map.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
map.invalidate();
Then create map overlay class in mapActivity
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw()
{
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}
i wrote the following code to get the coordinate of a address
package test;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.net.www.content.text.PlainTextInputStream;
public class a{
public static void main(String[] arg) throws Exception{
String address = "台北市信義路五段七號101樓";
// 查詢經緯度
String output = "csv";
String key = "";
String url = "http://maps.google.com/maps/geo?q=台北市信義路五段七號101樓&output=csv&key=ABQIAAAAXDq__hWKi9eMCwnn7LrMCxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSnSVp_Xlsd4Ph5iyMua7PE5E0x_A";
URL iurl = new URL(url);
HttpURLConnection uc = (HttpURLConnection)iurl.openConnection();
uc.connect();
Object content = uc.getContent();
// 讀取結果
PlainTextInputStream sr = (PlainTextInputStream)content;
byte[] buf = new byte[2000];
// 解析 200,8,25.033408,121.564099 (HTTP status code, accuracy, latitude, longitude)
sr.read(buf);
String[] tmpArray = new String(buf, "UTF-8").split(",");
String latitude = tmpArray[2];
String longitude = tmpArray[3];
}
}
The problem is that the content i got a 400 code in result
i put the url in the browser, it return a 200 instead.
Is there a way to do that in a none browser matter?
have u tried Google Geo Kit
http://gglgeo.codeplex.com/? it is also in Java.
This is a question-loaded post from someone who is just getting started with BB development. Any guidance is much appreciated.
How are map based BlackBerry apps such as Yelp and Google Map implemented? As with the web based version. Yelp for the BB allows you to search for restaurants & etc. based on on the current or specified location. The search result is in a form of a list or a map view displaying markers of the search results. Yelp's map is powered by Bing. How is the map, along with the markers, invoked within the BB code? For the list view, what is being used to retrieve the list of results from the database. Can any database be used?
Google Map 3.2 for the BB now supports layers. Again, how are the Google maps invoked? You can also select a marker (i.e. Wiki, gas station) of a particular location directly on the map and view the information of that location (i.e. Wiki, gas station address). How is this being done?
My knowledge in map technology as well as BB development is very limited, so basic or in depth feedback are both welcomed.
I have no experience of writing real-world gps applications for blackberry, below are just my observations and thoughts about possible workarounds.
Blackberry Yelp Application
Indeed, Blackberry Yelp application show map if you do search and then go into result and see Map Adress
alt text http://img197.imageshack.us/img197/965/13428830.jpgalt text http://img269.imageshack.us/img269/1976/92068364.jpg
See also Yelp Launches Bing-Powered Blackberry App
If you look into Yelp API you will find only search functionality which may optionally use Google Maps to display search result location on your website.
Bing seems to be MS analogue for Google Maps. And there is an ASP Bing Map Control which hardly can be used in BB development.
Blackberry Google Maps Application
alt text http://img193.imageshack.us/img193/9678/39917026.jpg
You can invoke installed Google Maps Mobile from code:
class Scr extends MainScreen {
public Scr() {
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(mInvokeGMaps);
}
MenuItem mInvokeGMaps = new MenuItem("Run GMaps", 0, 0) {
public void run() {
GMLocation location
= new GMLocation(51.507778, -0.128056, "London");
invokeGMaps(location);
};
};
public void invokeGMaps(GMLocation l) {
int mh = CodeModuleManager.getModuleHandle("GoogleMaps");
if (mh == 0) {
try {
throw new ApplicationManagerException(
"GoogleMaps isn't installed");
} catch (ApplicationManagerException e) {
System.out.println(e.getMessage());
}
}
URLEncodedPostData uepd = new URLEncodedPostData(null, false);
uepd.append("action", "LOCN");
uepd.append("a", "#latlon:" + l.getLatitude()
+ "," + l.getLongitude());
uepd.append("title", l.getName());
uepd.append("description", l.getDescription());
String[] args = { "http://gmm/x?" + uepd.toString() };
ApplicationDescriptor ad = CodeModuleManager
.getApplicationDescriptors(mh)[0];
ApplicationDescriptor ad2 = new ApplicationDescriptor(ad, args);
try {
ApplicationManager.getApplicationManager()
.runApplication(ad2, true);
} catch (ApplicationManagerException e) {
System.out.println(e.getMessage());
}
}
}
Using custom location class:
class GMLocation {
String mName;
String mDescription;
double mLatitude;
double mLongitude;
public GMLocation(double lat, double lon) {
mLatitude = lat;
mLongitude = lon;
}
public GMLocation(double d, double e, String name) {
this(d, e);
mName = name;
}
public GMLocation(double lat, double lon, String name, String descr) {
this(lat, lon, name);
mDescription = descr;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
public String getLongitude() {
return String.valueOf(mLongitude);
}
public String getLatitude() {
return String.valueOf(mLatitude);
}
}
See also How to use Google Map in Blackberry application?
Conclusion
Blackberry browser and BrowserField has a limited support of JavaScript. Since both Bing and GMaps are based on JavaScript, my suspicion is that they use static images retrieved from server to display map control. This may be possible but that means server side implementation and all required API developer keys.
As an alternative, you can invoke installed GMaps from code on Blackberry.