As the title, I'm confused with how to capture maps with MonoTouch, and how to get the location. As step by:
CLLocationManager locationManager = new CLLocationManager ();
locationManager.UpdatedLocation += UpdatedLocationEvent;
locationManager.Delegate = new MyLocationDelegate ();
locationManager.StartUpdatingLocation ();
class MyLocationDelegate : CLLocationManagerDelegate
{
public MyLocationDelegate () : base()
{
}
public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
{
Console.WriteLine ("newLocation " + newLocation.VerticalAccuracy + " " + newLocation.HorizontalAccuracy);
Console.WriteLine ("oldLocation " + oldLocation.VerticalAccuracy + " " + oldLocation.HorizontalAccuracy);
}
public override void Failed (CLLocationManager manager, NSError error)
{
Console.WriteLine ("Failed to find location");
}
}
It doesn't work. Please help me.
You have not configured the kind of events that you get, you are missing a line like this:
locationManager = new CLLocationManager () {
DesiredAccuracy = CLLocation.AccuracyBest,
Delegate = new MyCLLocationManagerDelegate (callback),
DistanceFilter = 1000f
};
if (CLLocationManager.LocationServicesEnabled)
locationManager.StartUpdatingLocation ();
Related
Hello i am creating App for iOS and Android. The issue i want to fix that on the load on page i want to display the map with the address. I can get Lat Long successfully but i cannot getting address that i want to display on a label. Below is my code that i am using.
using Plugin.Geolocator;
using Xamarin.Forms.Maps;
private Position _position;
// Map map;
double Lat, Long;
string address = "";
public TestPage()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
GetPosition();
if (_position != null)
{
Lat = _position.Latitude;
Long = _position.Longitude;
}
//Task<String> str = GetAddress();
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(Lat, Long), Distance.FromMiles(1)));
var position = new Position(Lat, Long);
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = ""
};
map.Pins.Add(pin);
var zoomLevel = 17.83;
var latlongdegrees = 360 / (Math.Pow(2, zoomLevel));
map.MoveToRegion(new MapSpan(position, latlongdegrees, latlongdegrees));
LabelTime.Text = DateTime.Now.ToString("hh:mm tt") + " " + DateTime.Now.ToString("MM/dd/yyyy");
string recentAddress = address; // trying to get adderss for location
}
GetPosition()
public async void GetPosition()
{
Plugin.Geolocator.Abstractions.Position position = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100.0;
position = await locator.GetLastKnownLocationAsync();
if (position != null)
{
_position = new Position(position.Latitude, position.Longitude);
//got a cahched position, so let's use it.
return;
}
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//not available or enabled
return;
}
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10), null, true);
}
catch (Exception ex)
{
// error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
}
_position = new Position(position.Latitude, position.Longitude);
if (position == null)
return;
}
GetAddress()
public async Task<String> GetAddress()
{
// string Addrsss = "";
try
{
Geocoder geoCoder = new Geocoder();
if (_position != null)
{
var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(_position);
await Task.Delay(2000);
foreach (var a in possibleAddresses)
{
address += a + "\n";
}
}
return address;
}
catch (Exception ex)
{
throw;
}
}
I also try to get the current address on OnAppearing()
protected override void OnAppearing()
{
this.Appearing += TestPage_Appearing; //Subscribe to event
base.OnAppearing();
}
protected async void TestPage_Appearing(object sender, EventArgs args)
{
GetPosition();
address= await GetAddress();
string a = address;
this.Appearing -= TestPage_Appearing; //Unsubscribe
}
You can get placemark address using Xamarin.Essentials as below,
protected async override void OnAppearing()
{
await GetAddress();
}
private async Task GetAddress()
{
var lat = 47.673988;
var lon = -122.121513;
var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);
var placemark = placemarks?.FirstOrDefault();
if (placemark != null)
{
var geocodeAddress =
$"AdminArea: {placemark.AdminArea}\n" +
$"CountryCode: {placemark.CountryCode}\n" +
$"CountryName: {placemark.CountryName}\n" +
$"FeatureName: {placemark.FeatureName}\n" +
$"Locality: {placemark.Locality}\n" +
$"PostalCode: {placemark.PostalCode}\n" +
$"SubAdminArea: {placemark.SubAdminArea}\n" +
$"SubLocality: {placemark.SubLocality}\n" +
$"SubThoroughfare: {placemark.SubThoroughfare}\n" +
$"Thoroughfare: {placemark.Thoroughfare}\n";
Console.WriteLine(geocodeAddress);
}
}
refer this link for in depth details
Also this one for detailed implementation
logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)
i am trying to choose form the autocomplete a place and drew a path to it and when i pick a place from the autocomplete the app crashes.
please see the
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.saoutimohamed.tewsila, PID: 5924
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown
Source:8)
at com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source:10)
at com.saoutimohamed.tewsila.WelcomeDriver$4.onResponse(WelcomeDriver.java:271)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
logcat and tall me what is wrong with my code
and this is the code
private void getDirection() {
String requestApi;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.d("SAOUTI", requestApi);
mService.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 5);
mMap.animateCamera(mCameraUpdate);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.GRAY);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(JointType.ROUND);
polylineOptions.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptions);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(5);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tewsila_car)));
handler = new Handler();
} catch (JSONException e) {
e.printStackTrace();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 3000);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(WelcomeDriver.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
the line that not responding in the logcat is (LatLngBounds bounds = builder.build();)
I had this same issue and i removed
"+getResources().getString(R.string.google_direction_api)" part from the requestApi. Perfectlr worked for me. But i don't know the reason.
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=";
Im using a MediaStreamSource to use the camera... everything works, except when I try to capture the image!
I think the problem is the object MediaStreamSource
public class CameraStreamSourceModel : MediaStreamSource
{
private MemoryStream _cameraStream = null; // here I've the stream from camera
...
public async void CapturePhoto()
{
// Save the image as a jpeg to the camera roll
MediaLibrary library = new MediaLibrary();
string filename = AppResources.ApplicationTitle + "_" + DateTime.Now.ToString("G");
Picture pic = library.SavePicture(filename, _cameraStream); //Here I've the exception
}
}
The exception is
System.InvalidOperationException: An unexpected error has occurred.
I've enabled ID_CAP_MEDIALIB_PHOTO.
I am sure the code to save image works because i can save static stream in media library, but not stream from camera!
Can anyone help me? Thank you
You could simply use a camera_capture_task
CameraCaptureTask cameraCaptureTask;
public Transaction()
{
InitializeComponent();
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
}
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
pic.Source = bmp;
pic_name = "" + DateTime.Now.Month + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second+".jpeg";
SaveToIsolatedStorage(e.ChosenPhoto, "" + pic_name);
}
}
Can anyone tell me how to use Google maps in blackberry application development instead of Blackberry map?
Recently I had an idea to use Google Maps website from Browser.Field but it's not possible since GMaps are based on JavaScript and it's badly supported by Blackberry native Browser.
Actually there are 2 ways of using Google Maps on Blackberry:
install Google Maps Mobile application (see example of use)
use Google Static Maps API to generate and send image on device request. This will require server-side implementation and Sign Up for the Google Maps API
Here is a little example:
The Form to view the Google Maps Static image:
public class frmMap extends Form implements CommandListener {
Command _back;
MIDlet midlet;
Form dis;
public frmMap(String title, ImageItem img, MIDlet m, Form d){
super(null);
this.midlet = m;
this.dis = d;
_back = new Command("Back", Command.BACK, 1);
addCommand(_back);
append(img);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if(c == _back){
Display.getDisplay(midlet).setCurrent(dis);
}
}
}
The class inet class to download the static image:
public class INETclass implements Runnable {
private String _location = null;
private HttpConnection inet;
private Pispaal _m;
public String url = null;
public INETclass(String location, Pispaal m){
_location = location;
_m = m;
}
public void run() {
try
{
//Setup the connection
inet = (HttpConnection)Connector.open(url);
inet.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
int rc = inet.getResponseCode();
//Responsecode controleren
if(rc == HttpConnection.HTTP_OK){
//Open input stream to read the respone
DataInputStream is = new DataInputStream(inet.openInputStream());
StringBuffer sb = new StringBuffer();
int ch;
long len = -1;
byte[] buffer = null;
if(_location == null){
len = is.available();
}
if(len != -1){
if(_location == null){
buffer = IOUtilities.streamToBytes(is);
}else{
while((ch = is.read()) != -1){
sb.append((char)ch);
}
}
}
is.close();
if(_location == null){
_m.OnINETComplete(buffer);
}else{
_m.Alert(sb.toString());
}
}else{
_m.Alert("URL " + url + " geeft response code: " + rc);
try
{
inet.close();
}catch(Exception e){
_m.Alert("Error: " + e.getMessage());
}
}
}
catch(Exception e)
{
_m.Alert("Error: " + e.getMessage());
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
if(inet != null){ inet.close(); }
Thread.currentThread().join(); //Making sure this thread dies
}catch(Exception e){
_m.Alert("Error: " + e.getMessage());
System.out.println("Error: " + e.getMessage());
}
}
}
}
The Button action that starts the download and the callback action that loads the form to view the image
public void commandAction(Command c, Displayable d) {
synchronized(c){
String loc = _location.getText();
if(loc.indexOf(",") > 0){
//if(c == _strCommand){
//INETclass inet = new INETclass(loc, this);
//Thread tInet = new Thread(inet);
//tInet.start();
//Alert("Locatie word doorgestuurd. Even geduld");
//}else
if(c == _mapView){
INETclass inet = new INETclass(null, this);
inet.url = "http://www.qeueq.com/gmap.php?location=" + this.lat + "," + this.lon + "&size=" + this.width + "x" + this.height + ";deviceside=true";
Thread tInet = new Thread(inet);
tInet.start();
}
}else{
Alert("GPS locatie is nog niet beschikbaar.");
}
}
}
public void UpdateLocation(double lat, double lon){
String location = lat + "," + lon;
this.lat = lat;
this.lon = lon;
synchronized(location){
_location.setText(location);
INETclass inet = new INETclass(location, this);
Thread tInet = new Thread(inet);
tInet.start();
}
}
Refine and edit the code so it fits your needs. Took me some time to get it right.
It is possible now to use Google Maps instead of BlackBerry maps with our own data like in the image.
If you're looking to use google maps to show your own locations/markers you can invoke google maps using ApplicationDescriptor from your application. Check for google maps on device using CodeModuleManager.getModuleHandle("GoogleMaps"); it returns an integer where non zero means it is available. Then you can add locations in your KML file, you can even customize location pointers using KML file tags.
The example as linked by Max allows a single marker only. So a KML file becomes necessary if multiple markers are to be added.
You may look at the simple tutorial here for beginners.