How to change camera angle of StreetViewPanoramaFragment? - android

StreetViewPanoramaFragment streetViewFragment = (StreetViewPanoramaFragment) getFragmentManager().findFragmentById(R.id.g_map_street);
streetViewFragment.getStreetViewPanoramaAsync(this);
#Override
public void onStreetViewPanoramaReady(StreetViewPanorama streetViewPanorama) {
streetView = streetViewPanorama;
streetViewPanorama.setPosition(new LatLng(Latitude, Longtitude));
}
I have a value of Heading which returns angle.
https://maps.googleapis.com/maps/api/streetview?size=800x800&location=%s,%s&heading=%s
Using it , I can get Streetview Image properly but not working in StreetViewPanoramaFragment.

Finally , after lots of R&D I found this solution.. and its works for me.
#Override
public void onStreetViewPanoramaReady(StreetViewPanorama streetViewPanorama) {
streetViewPanorama.setPosition(new LatLng(Latitude, Longtitude));
try {
//Change angle of street view
final int DURATION = 1000;
StreetViewPanoramaCamera camera = new StreetViewPanoramaCamera.Builder()
.zoom(streetViewPanorama.getPanoramaCamera().zoom)
.tilt(streetViewPanorama.getPanoramaCamera().tilt)
.bearing(streetViewPanorama.getPanoramaCamera().bearing + angle) // angle value by Maps Api
.build();
streetViewPanorama.animateTo(camera, DURATION);
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Google Place API For Android Map Point to Wrong Location (0,0) After Select an Address From Autocomplete

It works fine previously. I mean the code has not been changed since several months ago. This is what happen now, after I click an address from the autocomplete.
This is how I call the auto complete and the maps after pick a location.
private void openPlaceAutoComplete(){
try {
long touchTime = System.currentTimeMillis();
if(touchTime - latestTouchedTime > BOUNCE_DELAY){
latestTouchedTime = touchTime;
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this.getActivity());
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST);
}
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
Then, on ActivityResult
else if(requestCode == PLACE_AUTOCOMPLETE_REQUEST){
if(resultCode == Activity.RESULT_OK){
Place place = PlaceAutocomplete.getPlace(this.getFragmentBaseContext(), data);
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
builder.setLatLngBounds(LocationHelper.getBoundsFromCenter(place.getLatLng(), PLACE_BOUND_RADIUS));
try{
startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
}catch (GooglePlayServicesNotAvailableException ex){
ex.printStackTrace();
}catch (GooglePlayServicesRepairableException ex){
ex.printStackTrace();
}
}
}
I have make sure the place is not null, and it has LatLng object which is not 0,0 and GetBoundsFromCenter function is simply like this.
public static LatLngBounds getBoundsFromCenter(LatLng center, double radius){
LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225);
LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45);
return new LatLngBounds(southwest, northeast);
}
Unfortunately, this is a bug in the current release of the Place Picker. See https://stackoverflow.com/a/37318013/2994 for more info.

Android Google Maps Update Camera Before Snapshot Out of Order

I am trying to snapshot the Google Map image AFTER I set the map to the bounds of the Polyline. I have used separate code samples found on StackExchange to do both the moveToBounds() and Snapshot which work fine individually, but when run in sequence the Snapshot is of the map image BEFORE the map was updated. I assume I need to insert a OnCameraChangeListener but I cannot make it work. Do I need to somehow nest Callbacks? Please advise.
public void mapCapture() {
moveToBounds(gpsTrackingPolyline);
mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
public void onSnapshotReady(Bitmap bitmap) {
// Write image to disk
try {
File bmpFile = new File(getApplicationContext().getExternalFilesDir(null), DEFAULT_BMP_FILENAME);
FileOutputStream out = new FileOutputStream(bmpFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void moveToBounds(Polyline p)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
List<LatLng> arr = p.getPoints();
for(int i = 0; i < arr.size();i++){
builder.include(arr.get(i));
}
LatLngBounds bounds = builder.build();
int padding = 40; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
}
Don't know if you have found solution or if you still need it. But still here it goes. Yes you need a callback which will let you know when map has finished animation. Do something like this:
mMap.animateCamera(cu, new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
//your code related to snapshot
mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
public void onSnapshotReady(Bitmap bitmap) {
// Write image to disk
//rest of your code
});
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});

Azimuth coming back as 0

I am trying to get the azimuth of the users phone when they take a picture. However, when I put the azimuth to the screen just for debugging purposes currently, it always comes back at 0.0. I am new to using Sensors so I am trying to figure this out. My code is
private void dispatchTakePictureIntent() {
double latitude, longitude;
if (mGpsLocationTracker.canGetLocation()) {
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
} else {
latitude = 0;
longitude = 0;
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Toast.makeText(this, "" + latitude + ", " + longitude, Toast.LENGTH_SHORT).show();
getDirection ();
Toast.makeText(this, Float.toString(degree), Toast.LENGTH_SHORT).show();
}
public void getDirection() {
SensorManager mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> mySensors = mySensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if(mySensors.size() > 0){
mySensorManager.registerListener(mySensorEventListener, mySensors.get(0), SensorManager.SENSOR_DELAY_UI);
}
}
/*
DOES NOT WORK. NEED TO FIX
*/
private SensorEventListener mySensorEventListener = new SensorEventListener(){
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float radianValue = Math.round(event.values[0]);
degree = (float) Math.toDegrees(radianValue);
if (degree < 0.0f) {
degree += 360.0f;
}
}
};
public void takePicture (View view) {
dispatchTakePictureIntent();
}
Can anyone help me with what I'm doing wrong
Doesn't the orientation sensor return the angle in degrees? You're assuming radians and converting to degrees. Given that though, it still should't give you 0.
TYPE_ORIENTATION is depreciated and does not give the correct result
if the device is not flat. You need to use TYPE_ACCELEROMETER and TYPE_MAGNETIC_FIELD to obtain the rotation matrix and then call remapCoordinateSystem before calling getOrientation.

Loading 1700 markers on Google Map v2 Android timing out

I have a file with about 1700 markers that I am trying to load onto a gmap v2. On my galaxy nexus running 4.2.2 it loads no problem, but some folks with 4.0.x and 4.1.x are not having the same results. They get the map, but no points or the app crashes after about 30 seconds. I am loading a local file...
Here is my method:
public void BuildMap() {
FileInputStream fXmlFile;
markerInfo = new HashMap<Marker, MapMarkers>();
try {
fXmlFile = new FileInputStream(
"/storage/emulated/0/snoteldata/kml/snotelwithlabels.kml");
XmlDom xml = new XmlDom(fXmlFile);
List<XmlDom> locations = xml.tags("Placemark");
String Name, Description, Lat, Lon;
markerInfo = new HashMap<Marker, MapMarkers>();
for (XmlDom location : locations) {
MapMarkers marks = new MapMarkers();
Name = location.tag("name").text();
Description = location.tag("description").text();
Lat = location.tag("latitude").text();
Lon = location.tag("longitude").text();
la = Float.parseFloat(Lat);
lo = Float.parseFloat(Lon);
marks.setTitle(Name);
marks.setDesc(Description);
Marker m = map.addMarker(new MarkerOptions()
.position(new LatLng(la, lo))
.title(marks.getTitle())
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.snotel_marker)));
markerInfo.put(m, marks);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
MapMarkers markInfo = markerInfo.get(marker);
Intent i = new Intent(MainActivity.this,
MarkerInformation.class);
i.putExtra("name", markInfo.getTitle()).putExtra(
"description", markInfo.getDesc());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
}
} catch (SAXException e) {
// TODO Auto-generated catch block
Log.e("SAXException", e.getMessage());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("FileNotFoundException", e.getMessage());
}
}
I have tried putting this in a AsyncTask, but get the Not on Main Thread error each time... so I am not sure how to run it in the background to keep it loading for folks until the parsing has completely happened.
Why does this show for my Gnex and a Nexus 7 tablet, but not for 4.0.x etc??? How can I figure out where the issue is on others devices?
There are two problems with your code.
First, you are reading file on the main thread. Do this part in background, e.g. using AsyncTask which returns a list of MarkerOptions. Iterate over returned list in onPostExecute to add those to the map.
Second issue might be the amount of Markers. There are a few ways to handle this. Check this answer: Add markers dynamically on Google Maps v2 for Android
Do this way
public void BuildMap() {
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
FileInputStream fXmlFile;
markerInfo = new HashMap<Marker, MapMarkers>();
try {
fXmlFile = new FileInputStream("/storage/emulated/0/snoteldata/kml/snotelwithlabels.kml");
XmlDom xml = new XmlDom(fXmlFile);
List<XmlDom> locations = xml.tags("Placemark");
String Name, Description, Lat, Lon;
markerInfo = new HashMap<Marker, MapMarkers>();
for (XmlDom location : locations) {
final MapMarkers marks = new MapMarkers();
Name = location.tag("name").text();
Description = location.tag("description").text();
Lat = location.tag("latitude").text();
Lon = location.tag("longitude").text();
la = Float.parseFloat(Lat);
lo = Float.parseFloat(Lon);
marks.setTitle(Name);
marks.setDesc(Description);
mHandler.post(new Runnable() {
#Override
public void run() {
Marker m = map.addMarker(new MarkerOptions().position(new LatLng(la, lo)).title(marks.getTitle())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.snotel_marker)));
markerInfo.put(m, marks);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
MapMarkers markInfo = markerInfo.get(marker);
Intent i = new Intent(MainActivity.this, MarkerInformation.class);
i.putExtra("name", markInfo.getTitle()).putExtra("description", markInfo.getDesc());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
}
});
}
} catch (SAXException e) {
// TODO Auto-generated catch block
Log.e("SAXException", e.getMessage());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("FileNotFoundException", e.getMessage());
}
}
}).start();
}

How to take google Maps v2 snapshot?

i have to solve this with the new "snapshot maker" which is implemented in the google maps release august but i dont' know how to do this.
Can somone give me a simple example?
here is my code:
public class MainActivity extends Activity {
static LatLng HAMBURG = new LatLng(47.524749, 21.632745);
GoogleMap map;
File dbFile;
private File imageFile;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PolylineOptions line = new PolylineOptions();
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
/*
* Adatbázis
*/
try {
dbFile = getDatabasePath("/mnt/sdcard/Download/TeleSensors.db");
} catch (Exception e) {
}
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(
dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
Cursor curTAB = myDataBase.rawQuery("SELECT * FROM GPS_Values;", null);
Integer count = 0;
while (curTAB.moveToNext()) {
String s_latitude = curTAB.getString(1);
String s_longitude = curTAB.getString(2);
count++;
double latitude = Double.parseDouble(s_latitude);
double longitude = Double.parseDouble(s_longitude);
line.add(new LatLng(latitude, longitude));
Log.i("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString());
}
curTAB.close();
myDataBase.close();
// adatbázis vége
map.addPolyline(line);
// map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// map.setMapType(GoogleMap.MAP_TYPE_NONE);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
}
Thank you very mouch!
You have to call the Google maps snapshot method in a button listener because if you should take it too early, it will give you error bitmap width has to be larger than 0 or something like this.
Here is the code
private void button_listener() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/Download/TeleSensors.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
}
});
}
This one is better, it waits for your Map to be fully rendered, before taking the snapshot.
It was updated on 31-Oct-2013.
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
public void onMapLoaded() {
mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
public void onSnapshotReady(Bitmap bitmap) {
// Write image to disk
FileOutputStream out = new FileOutputStream("/mnt/sdcard/map.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
});
}
});
Extracted from http://googlegeodevelopers.blogspot.sg/2013/10/ghost-markers-in-your-neighborhood-new.html
Try for Kotlin Android like this when click on button to take google map snapshot:
val snapshotReadyCallback : GoogleMap.SnapshotReadyCallback = GoogleMap.SnapshotReadyCallback { selectedScreenShot ->
ivMapPreview.setImageBitmap(selectedScreenShot);
}
val onMapLoadedCallback : GoogleMap.OnMapLoadedCallback = GoogleMap.OnMapLoadedCallback {
mMap!!.snapshot(snapshotReadyCallback)
}
mMap!!.setOnMapLoadedCallback(onMapLoadedCallback)
Be successful.
I' ve tried the accepted answer but it didn't work then tried another approach that worked for me.
private void CaptureScreen() {
if(initMap()){
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap=null;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
saveImage(bitmap);
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
};
mMap.snapshot(callback);
}
else{
Toast.makeText(this, "Map is not Initialized yet", Toast.LENGTH_LONG).show();
return ;
}
}
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/GoogleMap#snapshot(com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback, android.graphics.Bitmap)
public final void snapshot (GoogleMap.SnapshotReadyCallback callback)
Takes a snapshot of the map. You can use snapshots within your application when an interactive map would be difficult, or impossible,
to use. For example, images produced with the snapshot() method can be
used to display a thumbnail of the map in your app, or a snapshot in
the notification center.

Categories

Resources