I am a beginner of Android Developer. I am developing the Map Application. I have a function of searching address but I do not know how to search address by name using Google Map API V.2. Please suggest me the solution and some code to solve this. Thank you very much and Sorry with my English.
adderess = c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
// get address in string for used location for the map
/* get latitude and longitude from the adderress */
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocationName(adderess, 5);
if (addresses.size() > 0)
{
Double lat = (double) (addresses.get(0).getLatitude());
Double lon = (double) (addresses.get(0).getLongitude());
Log.d("lat-long", "" + lat + "......." + lon);
final LatLng user = new LatLng(lat, lon);
/*used marker for show the location */
Marker hamburg = map.addMarker(new MarkerOptions()
.position(user)
.title(adderess)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(user, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
}
catch (IOException e)
{
e.printStackTrace();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_map);
editText = (EditText) findViewById(R.id.editText1);
mapView = (MapView) findViewById(R.id.mapView);
btngo = (Button) findViewById(R.id.btnmapsites);
btngo.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
List<Address> addresses;
try{
addresses = geoCoder.getFromLocationName(editText.getText().toString(),1);
if(addresses.size() > 0){
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 = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
editText.setText("");
}else{
AlertDialog.Builder adb = new AlertDialog.Builder(SearchMapActivity.this);
adb.setTitle("Google Map");
adb.setMessage("Please Provide the Proper Place");
adb.setPositiveButton("Close",null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Related
I'm currently developing an android application that would allow users to draw Polylines with Markers or point in the polyline when user long press on points how to dragline with points move also line would be move on the map. how do I achieve this I drag marker but cant move marker
public class MainMapActivity extends AppCompatActivity {
GeoPoint startPoint;
MapView map;
Road road;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_map);
map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
GpsTracking gps=new GpsTracking(MainMapActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
startPoint = new GeoPoint(latitude, longitude);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
// GeoPoint startPoint = new GeoPoint(48.13, -1.63);
IMapController mapController = map.getController();
mapController.setZoom(17);
mapController.setCenter(startPoint);
Marker startMarker = new Marker(map);
startMarker.setPosition(startPoint);
startMarker.setDraggable(true);
startMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
map.getOverlays().add(startMarker);
//Set-up your start and end points:
RoadManager roadManager = new OSRMRoadManager(this);
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(31.382108, 74.260107);
waypoints.add(endPoint);
// retreive the road between those points:
Road road = roadManager.getRoad(waypoints);
// build a Polyline with the route shape:
Polyline polyline=new Polyline();
polyline.setOnClickListener(new Polyline.OnClickListener() {
#Override
public boolean onClick(Polyline polyline, MapView mapView, GeoPoint eventPos) {
return false;
}
});
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
//Polyline to the overlays of your map:
map.getOverlays().add(roadOverlay);
//Refresh the map!
map.invalidate();
//3. Showing the Route steps on the map
FolderOverlay roadMarkers = new FolderOverlay();
map.getOverlays().add(roadMarkers);
Drawable nodeIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.marker_node, null);
for (int i = 0; i < road.mNodes.size(); i++) {
RoadNode node = road.mNodes.get(i);
Marker nodeMarker = new Marker(map);
nodeMarker.setDraggable(true);
nodeMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
nodeMarker.setPosition(node.mLocation);
nodeMarker.setIcon(nodeIcon);
//4. Filling the bubbles
nodeMarker.setTitle("Step " + i);
nodeMarker.setSnippet(node.mInstructions);
nodeMarker.setSubDescription(Road.getLengthDurationText(this, node.mLength, node.mDuration));
Drawable iconContinue = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_continue, null);
nodeMarker.setImage(iconContinue);
//4. end
roadMarkers.add(nodeMarker);
}
}
class OnMarkerDragListenerDrawer implements Marker.OnMarkerDragListener {
ArrayList<GeoPoint> mTrace;
Polyline mPolyline;
OnMarkerDragListenerDrawer() {
mTrace = new ArrayList<GeoPoint>(100);
mPolyline = new Polyline();
mPolyline.setColor(0xAA0000FF);
mPolyline.setWidth(2.0f);
mPolyline.setGeodesic(true);
map.getOverlays().add(mPolyline);
}
#Override public void onMarkerDrag(Marker marker) {
//mTrace.add(marker.getPosition());
}
#Override public void onMarkerDragEnd(Marker marker) {
mTrace.add(marker.getPosition());
mPolyline.setPoints(mTrace);
map.invalidate();
}
#Override public void onMarkerDragStart(Marker marker) {
//mTrace.add(marker.getPosition());
}
}
}
Does anyone know how I can achieve this? above is a snippet of my codes. Thanks!
I am using android studio 0.8.9. i am using google map v2 and google services 5.2.08.i want to display marker from given address and also generated SHA Key using key-tool also enabled and get my API Key from google console. But when i am using GeoPoint for getting Lat and Long android studio does not recognize GeoPoint class.
My Java Activity code:
public class WelcomeUser extends ActionBarActivity {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_user);
try {
if(null == googleMap){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.mapView)).getMap();
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if(null == googleMap) {
Toast.makeText(getApplicationContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
double lat= 0.0, lng= 0.0;
String address = "Ahmedabad, Gujarat";
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocationName(address , 1);
if (addresses.size() > 0)
{
GeoPoint p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
lat=p.getLatitudeE6()/1E6;
lng=p.getLongitudeE6()/1E6;
Log.d("Latitude", ""+lat);
Log.d("Longitude", ""+lng);
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(null != googleMap){
googleMap.addMarker(new MarkerOptions()
.position(p)
.title("Marker")
.draggable(true)
);
}
}
Please help me guys.Thanks in advance
Geocoder no longer provided latitude-longitude from addresses,use Reverse Geocoding API to get latitude-longitude from address.
Check Example here : Get latitude,longitude from address in Android
I am trying to buid a simple app that when user enter his desired location its map appear.But i am getting an error Cannot instantiate the type GeoPoint i have also installed Google Play Services.
here is the code :
public class MainActivity extends MapActivity {
EditText location;
Geocoder geoCoder;
GeoPoint p;
MapController controller;
MapView mapView;
Button btnSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location=(EditText)findViewById(R.id.txtAddress);
mapView = (MapView) findViewById(R.id.mapView);
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
List<Address> addresses;
try {
addresses = geoCoder.getFromLocationName(location.getText().toString(),1);
if(addresses.size() > 0)
{
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 = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
location.setText("");
}
else
{
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Google Map");
adb.setMessage("Please Provide the Proper Place");
adb.setPositiveButton("Close",null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Is there a particular reason you need to use v1 of the Google maps api, instead of the current v2? If not, try using LatLng to store the location, and map.moveCamera(LatLng, float zoom) to go to the desired location as shown here.
I want to get map location by name.
But map is not showing lcoation. My code is given below:
SupportMapFragment fm = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
if (googleMap != null)
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
Geocoder geoCoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName("Ferozepur Rd Lahore", 1);
if (addresses.size() > 0) {
int lat = (int) (addresses.get(0).getLatitude() * 1E6);
int longt = (int) (addresses.get(0).getLongitude() * 1E6);
p = new GeoPoint(lat,longt);
LatLng latLng = new LatLng(lat, longt);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(new MarkerOptions().position(new LatLng(lat, longt)).title("Hello world"));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
} catch (IOException e) {
e.printStackTrace();
}
But it is showing me this result:
Latitude and longitude itself you didnt shown.code is incomplete.However Use Mapview balloons.
https://github.com/jgilfelt/android-mapviewballoons
I have this textbox in the other activity and a button which leads to this map. What i want to do is that it allows the user to click the map and pin point the location they wants, and they can also fetch that location's address back to the textbox without typing. Can it be done so? Since now there is this alert dialog box which pop up after user pin point it with 2 buttons(Yes and No) So if yes, fetch that location address back to the textbox. Any idea?
static EditText txtLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
MapOverlay mapOverlay = new MapOverlay();
mapOverlays.add(mapOverlay);
// obtain gps location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}
p = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
mc.animateTo(p);
mc.setZoom(18);
// Add a location marker
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listofOverlays = mapView.getOverlays();
listofOverlays.clear();
listofOverlays.add(mapOverlay);
// invalidate() method forces the MapView to be redrawn
mapView.invalidate();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean onTap(final GeoPoint p, MapView mapView) {
// TODO Auto-generated method stub
k = p;
mc = mapView.getController();
mc.animateTo(p);
mapView.invalidate();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
// txtLocation.setText(add);
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Change location..")
.setMessage("go to the new location?")
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
txtLocation.setText(add);
// Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
}
}).show();
return true;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
if (k != null) {
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(k, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x - 10, screenPts.y - 34, null);
}
return true;
}
}
}
Well you can try reverse geocoding. What that needs is you to supply the lat long of the point that the user tapped on, which is fairly easy.
Check this similar question. might help.