I am trying to get a precipitation weather layer to appear in my Google Maps activity, but cannot understand why it is not showing on the map. I have implemented my Google Maps Key in app\src\debug\res\values\google_maps_api.xml, have installed Google Play Services in Android SDK manager, and I have set up an account with OpenWeatherMap for their API (which is taken out below).
The map loads fine, and when I search the layer in a separate browser with inputted zoom,x,y it shows up fine, but I cannot get the layer to appear on my Google Maps activity.
Do I need to define x,y,zoom or are these pulled from the URL?
Here is my java:
package com.example.user.project;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.UrlTileProvider;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Move the camera
LatLng indy = new LatLng(39, -86.5);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(indy, 8));
TileProvider tileProvider = new UrlTileProvider(256, 256) {
#Override
public URL getTileUrl(int x, int y, int zoom) {
/* Define the URL pattern for the tile images */
String s = String.format(Locale.US, "http://tile.openweathermap.org/map/precipitation/%d/%d/%d.png?appid={my_key}",
zoom, x, y);
if (!checkTileExists(x, y, zoom)) {
return null;
}
try {
return new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
}
/*
* Check that the tile server supports the requested x, y and zoom.
* Complete this stub according to the tile range you support.
* If you support a limited range of tiles at different zoom levels, then you
* need to define the supported x, y range at each zoom level.
*/
private boolean checkTileExists(int x, int y, int zoom) {
int minZoom = 12;
int maxZoom = 16;
return !(zoom < minZoom || zoom > maxZoom);
}
};
TileOverlay tileOverlay = mMap.addTileOverlay(new TileOverlayOptions()
.tileProvider(tileProvider));
}
}
Here is the Android Studio generated layout:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.project.MapsActivity"/>
I have followed tutorials and documentation offered from OpenWeatherMap, Google Maps API, and Android Developers, but do not understand why this is not working.
What am I missing?
You are setting level 8 as zoom level for your map but you are also limiting zoom levels to be between 12 and 16 for your TileProvider to be visible.
Remove this:
if (!checkTileExists(x, y, zoom)) {
return null;
}
If you don't need any scale restriction you can also remove the checkTileExists method.
Related
Hi I wanted to know how I can get JSON data from a URL and put that into a map activity in android studio, which would replace the default location, which is syndey? I cannot figure out how to do this as most tutorials online not make sense.
This is the data, which I want to retrieve via the URL
{"Users":[{"name":"Diaz","lon":"51.1251635","lat":"51.296910"},{"name":"Chris","lon":"51.139409","lat":"51.295825"}}
This is the default code generated by the map activity
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GoogleMap nMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(512.33,11.2333);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydeny));
mMap.getMaxZoomLevel();
}
}
Firstly, to display your current location on the map. All you need to do is get the co-ordinate of your preferred location using google map. You can now create a LatLng object using this value.
Your app currently displays sidney because that is where the Map camera is position. You also have a marker at that same LatLng.
You can simple get the coordinates of where ever location you want to display and pass it into the Map object.
Back to your main question which is getting a JSON data from a URL; i can say that it is pretty easy to achieve and based on the context from which you are asking, i can infer that you are maybe trying to query the google map api.
A library like Retrofit(http://square.github.io/retrofit/) would help you get this done easily.
Just do not forget to execute the operation from a background thread.
Using basic HttpURLConnection
public JSONObject queryGoogleDistanceApi(String origin, String destination, String API_KEY_PLACES) throws Exception{
String Url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + origin + "&destinations=" + destination + "&mode=driving&language=en&key=" + API_KEY_PLACES;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
URL url = new URL(Url);
Log.d(TAG, Url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
if (conn != null) {
conn.disconnect();
}
JSONObject object = new JSONObject(jsonResults.toString());
return object;
}
you must call your api in onMapReady method. then parse it and set markers from your data. like below code:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//call your api. get son data
//{"Users":[{"name":"Diaz","lon":"51.1251635","lat":"51.296910"},{"name":"Chris","lon":"51.139409","lat":"51.295825"}}
// Add a marker from JSON data, and move the camera.
LatLng diaz = new LatLng(51.296910,51.1251635);
mMap.addMarker(new MarkerOptions().position(diaz).title("Diaz"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(diaz));
mMap.getMaxZoomLevel();
}
I think that you can parse Json data. if you have problem in parse Json data, I can help you again.
How can I add multiple markers in my mapAcivity and launch into new acttivity by clicking on that marker. What I want to do is that when user searches for specific location in google map v2. He should be able to mark that location on click and launch into a new dialog activity, and then different actions will be called based on the co-ordinates of location. So far I have integrated the map but can't figure out how to add multiple markers. So far the code is
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
//import com.javaorigin.test.apk.R;
public class MapsActivity extends FragmentActivity
{
private GoogleMap newmap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Log.d("Map","MapCreated");
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #newmap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (newmap == null) {
// Try to obtain the map from the SupportMapFragment.
newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (newmap != null) {
setUpMap();
Log.d("MAPS","Map working");
}
else Log.d("MAPS","not working");
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #newmap} is not null.
*/
private void setUpMap() {
newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
newmap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
newmap.setTrafficEnabled(true);
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
LatLng two = new LatLng(latitude+0.00005, longitude);
LatLng three = new LatLng(latitude+0.00007, longitude);
LatLng four = new LatLng(latitude+0.00009, longitude);
// Show the current location in Google Map
newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));
newmap.addMarker(new MarkerOptions().position(two).title("two"));
newmap.addMarker(new MarkerOptions().position(three).title("three"));
newmap.addMarker(new MarkerOptions().position(four).title("four"));
Log.d("LATITUDE",String.valueOf(latitude));
Log.d("LONGITUDE",String.valueOf(longitude));
}
}
OnMarkerClickListener listener = new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
startActivity();
return true;
}
};
newmap.setOnMarkerClickListener(listener);
newmap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
I record a video from Samsung Galaxy S4 (1080wx1920h) from FRONT CAMERA.
The resulting video is rotated 90° and upside down. (See the picture)
Then I take the video (final resolution 320wx240h) and I display it to TextureView with:
textureView.setRotation(90.0f);
textureView.setScaleX(-1);
and I set the layout parameters of the textureView to:
ViewGroup.LayoutParams params = textureView.getLayoutParams();
params.height = 1440;
params.width = 1080;
textureView.setLayoutParams(params);
The result looks like:
After several retries I figgured that if I set layout to:
params.height = 810;
params.width = 1080;
The dimensions ration remains correct:
Finally I would like to display the video as it was recorded in RecordingActivity (1080wx1440h):
Any thoughts on how to accomplish this?
Or is there a way how to record the video from front camera in correct rotation?
Full activity code:
import android.app.Activity;
import android.graphics.Point;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.TextureView;
import android.view.ViewGroup;
public class ReplayActivity extends Activity implements TextureView.SurfaceTextureListener {
private String pathToVideo;
private TextureView textureView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_replay);
textureView = (TextureView)findViewById(R.id.texture_view);
textureView.setSurfaceTextureListener(this);
textureView.setRotation(90.0f);
textureView.setScaleX(-1);
pathToVideo = getIntent().getStringExtra("path");
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setSurface(new Surface(surface));
try {
mediaPlayer.setDataSource(pathToVideo);
mediaPlayer.prepare();
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);//x = 1080, y = 1920
Point videoDimensions = new Point(mediaPlayer.getVideoWidth(),mediaPlayer.getVideoHeight());//x = 320, y = 240
Point resultParams = VideoHelpers.getScaledDimension(new Point(videoDimensions.y * 1000, videoDimensions.x * 1000), size);//x = 1080, y = 1440
ViewGroup.LayoutParams params = textureView.getLayoutParams();
params.height = resultParams.y;//1440
params.width = resultParams.x;//1080
textureView.setLayoutParams(params);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {return false;}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000">
<TextureView
android:id="#+id/texture_view"
android:layout_width="wrap_content"
android:background="#000000"
android:layout_height="wrap_content" />
</RelativeLayout>
Playing with the camera, the previews, the textures, adn the matrix can be tricky.
Have in mind that the natural orientation of the camera is landscape, so if you dont do anything else, the resulting video will be in that orientation. Also, the preview frames will be landscape.
when you do textureView.setRotation(90.0f); and textureView.setScaleX(-1); you are only modifying the internal transformation matrix of the texture, this is, when something is drawed inside, a transformation occurs, and what you see is different of the actual content. This is fine, but actually the camera dont know anything about this rotation and neither the mediarecorder.
If you are using Mediarecorder You should take a look at
MediaRecorder.html#setOrientationHint(int)
Sets the orientation hint for output video playback. This method
should be called before prepare(). This method will not trigger the
source video frame to rotate during video recording, but to add a
composition matrix containing the rotation angle in the output video
if the output format is OutputFormat.THREE_GPP or OutputFormat.MPEG_4
so that a video player can choose the proper orientation for playback.
Note that some video players may choose to ignore the compostion
matrix in a video during playback.
Parameters
degrees the angle to be rotated clockwise in degrees. The
supported angles are 0, 90, 180, and 270 degrees.
If you are using other recording approach, probably you shold take a look at
Camera.Parameters.html#setRotation(int)
or
Camera.html#setDisplayOrientation(int)
I've done the prep work of finding accurate latitude/longitude (in decimal number notation) coordinates for all 6 Hooters restaurant locations in Wisconsin. I intend to store those coordinate values in an array of a separate class. I also already have a Location Listener in my code to get the user's current GPS location. See my code below:
package sam.finalmap.hooters;
// Camera is the view of the map.
import com.google.android.gms.maps.CameraUpdateFactory;
// the google map
import com.google.android.gms.maps.GoogleMap;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color; // for drawing a line.
import android.location.Location; // for detecting location changes with the GPS.
import android.location.LocationListener; // to listen for location changes
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.MapFragment; // the Map class.
import com.google.android.gms.maps.model.LatLng; // for creating lattitudes and longitutes in memory.
import com.google.android.gms.maps.model.Polyline; // used to draw from one location to the other
import com.google.android.gms.maps.model.PolylineOptions;
/**
* Draws a map, uses GPS to get the current location, the draws a line from Eau CLaire (see constants)
* to the new position, which will be the closest Hooters restaurant to the user's current location.
* This is the AdapterView.
*
* #author daviddalsveen
*
*/
public class GMapsLocationPath extends Activity implements LocationListener {
/** Called when the activity is first created. */
private GoogleMap mMap;
// constants to hard code all 6 of Wisconsin's Hooters restaurant points on the map:
private static final float Appleton_LAT = 44.2655012f;
private static final float Appleton_LNG = -88.4768057f;
private static final float Brookfield_LAT = 43.03645f;
private static final float Brookfield_LNG = -88.124937f;
private static final float EastMadison_LAT = 43.132432f;
private static final float EastMadison_LNG = -89.3016256f;
private static final float GreenBay_LAT = 44.477903f;
private static final float GreenBay_LNG = -88.067014f;
private static final float Janesville_LAT = 42.7215666f;
private static final float Janesville_LNG = -88.9889661f;
private static final float LaCrosse_LAT = 43.8109318f;
private static final float LaCrosse_LNG = -91.2536215f;
private LocationManager locationManager;
private TextView tv; // a Textview for displaying lattitude and longitude.
private float curLat = 44.88f; // current position -- assigned constants for
// testing...
private float curLng = -91.47f;
#Override
public void onCreate(Bundle savedInstanceState) {
// called when the activity is first started.
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// recommended method by google to make the map object.
setUpMapIfNeeded();
// Sets the map type to be "normal"
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
tv = (TextView) findViewById(R.id.label1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 1, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// 500 is the minimum time interval to update, in milliseconds
// 1 is the distance in meters in which to sense an update.
// 'this' is the pending intent.
// center latitude and longitude for EC
float lat = Appleton_LAT;
float lng = Appleton_LNG;
// debug example...
Toast.makeText(this, "" + (int) (lat * 1E6), Toast.LENGTH_LONG).show();
if (location == null) { // no last known location
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
this, null);
// Create a new Lattitude Longitude Object, passing it the
// coordinates.
LatLng latLng = new LatLng(lat, lng);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.0f));
// re-draw
} else {
// explicitly call and update view with last known location or the
// one set above.
onLocationChanged(location);
}
}
/**
* Checks to see that the map exists, if not, creates one.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}// else?
}
}
// Java Interface RULE NOTE: that we must implement every method of
// interface LocationListener,
// whether we use the method or not.
/**
* Use the GPS to get the current location of the user
*
*/
public void onLocationChanged(final Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
Log.e("GPS", "location changed: lat=" + lat + ", lon=" + lon);
tv.setText("lat=" + lat + ", lon=" + lon);
curLat = Float.parseFloat(lat); // update the current lattitude and longitude.
curLng = Float.parseFloat(lon);
// Create a new Lattitude Longitude Object, passing it the coordinates.
LatLng latLng = new LatLng(curLat, curLng);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.0f));
// re-draw
draw();
}
public void onProviderDisabled(String loc) {
Log.e("GPS", "provider disabled " + loc);
}
public void onProviderEnabled(String loc) {
Log.e("GPS", "provider enabled " + loc);
}
/**
* loc: name of location provider status: status of location provider
* (temporarily unavailable, etc) extras: optional bundle with additional
* status information
*/
public void onStatusChanged(String loc, int status, Bundle extras) {
Log.e("GPS", "status changed to " + loc + " [" + status + "]");
}
/**
* Draw a line from
*/
public void draw() {
float lat = 44.88f;
float lng = -91.48f;
// Instantiates a new Polyline object and adds points to define a
// endpoints of a line
PolylineOptions rectOptions = new PolylineOptions().add(
new LatLng(curLat, curLng))
.add(new LatLng(lat, lng)); // Closes the polyline.
// Set the rectangle's color to red
rectOptions.color(Color.RED);
// Get back the mutable Polyline
Polyline polyline = mMap.addPolyline(rectOptions);
}
}
What I want help with here is finding a way to parse through the array, and compare the difference of the user's location with each of the 6 restaurant locations, and whichever difference is smallest (whichever restaurant location is closest to the user) is the restaurant that will be selected and who's information will displayed.
That said, how do I tell it to use the smallest difference after it finishes parsing through the array and getting all 6 of the latitude/longitude differences?
/**
* My teacher suggested subtracting the current latitudes and longitudes from the restaurant latitudes and
* longitudes to see if they fall within a certain range (lets just say less than 10). Then, using the resulting
* differences as absolute values in an if statement (if absolute value < 10 for both are true), that restaurant
* would be the one selected:
*/
//float[] H_Latitude = {44.2655012f, 43.03645f, 43.132432f, 44.477903f, 42.7215666f, 43.8109318f};
//float[] H_Longitude = {-88.4768057f, -88.124937f, -89.3016256f, -88.067014f, -88.9889661f, -91.2536215f};
float LATdifference = curLat - H_Latitude;
float LNGdifference = curLng - H_Longitude;//I'm pretty sure I can't use "H_Longitude and H_Latitude", because
//they're merely the name of the array. So how do I access the elements inside of them? How do I successfully
//address them with a reference variable that I can use to dynamically subtract from curLat and curLng and get
//what I need to replace the "i" in the for loops:
for (float LATdifference = 0; i < 4; i++) {
System.out.println (count[i]);
}
Try Location.distanceBetween(): reference
You could feed the GPS coordinates into the Google Directions API and use the travel distance to determine the closest store.
The Android Location class has a distanceTo or distanceBetween method that you could use to get a straight line distance between 2 GPS points. You could use this to narrow it down to 2-3 candidates and then use the directions api to get a final answer.
I have a map that I want to put a marker on, but the marker isn't showing up. Here is my code:
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
public class MapDetailActivity extends MapActivity
{
private final static String TAG = MapDetailActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.map_view);
// get longitude and latitude values from detail activity/object
Bundle bundle = this.getIntent().getExtras();
float latitude = bundle.getFloat("uie.top25.seattle.latitude");
float longitude = bundle.getFloat("uie.top25.seattle.longitude");
Log.i(TAG, "Latitude that is set : " + latitude);
Log.i(TAG, "Longitude that is set : " + longitude);
// create longitude and latitude map points
Double lat = latitude * 1E6;
Double lon = longitude * 1E6;
// create point on map
GeoPoint point = new GeoPoint(lat.intValue(), lon.intValue());
OverlayItem oi = new OverlayItem(point, null, null);
MapView mapView = (MapView) this.findViewById(R.id.myMapView);
MapController mapController = mapView.getController();
// set point on map
mapController.animateTo(point);
oi.setMarker(oi.getMarker(R.drawable.mm_20_red));
// set zoom level
mapController.setZoom(19);
}
#Override
protected boolean isRouteDisplayed()
{
// No driving directions, so this method returns false
return false;
}
}
Can someone tell me what I am doing wrong?
You must add your item to map using https://developers.google.com/maps/documentation/android/hello-mapview this documentation Part-2
You need to create an Overlay to display a marker, read this:
https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/Overlay
If you couldn't be bothered reading all of that here's a ready to use tutorial:
http://android-er.blogspot.com/2009/11/display-marker-on-mapview-using.html
You will need to go through the documentation and examples, but the basic steps are:
1-Create your itemizedOverlay by extending the itemizedOverlay from google maps.
2-Add an overlay Item to your Itemized overlay, and set the marker or use the default one defined in the previous step.
3-Add the itemized overlay to the mapview overlays with:
mapview.getoverlays().add(myItemizedOverlay);
Just after you have add the overlay to the mapview overlays list, the overlay will be considered by mapview to be called for drawing on screen (calling the onDraw method)
good luck.