2014-11-14 4 views
-1

Я создаю приложение для Android и использую mapActivity.Как использовать MapActivity в android?

Но проблема в том, что отображение ящика при запуске приложения не происходит.

Вот мой код активность:

public class MainActivitytut extends FragmentActivity{ 

GoogleMap map; 
private static MapController mMapController; 
private static final LatLng GOLDEN_GATE_BRIDGE = 
     new LatLng(37.828891,-122.485884); 
private static final LatLng APPLE = 
     new LatLng(37.3325004578, -122.03099823); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maintut); 

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); 
    if (map == null) { 
     Toast.makeText(this, "Google Maps not available", 
      Toast.LENGTH_LONG).show(); 

    } 
} 


Вот мой XML:

<RelativeLayout 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
xmlns:android="http://schemas.android.com/apk/res/android"> 

<fragment 
android:id="@+id/map" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
class="com.google.android.gms.maps.SupportMapFragment" /> 

<TextView 
android:id="@+id/locinfo" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_alignParentTop="true" 
android:layout_marginLeft="104dp" 
android:layout_marginTop="113dp" 
android:text="TextView" /> 

</RelativeLayout> 


Вопрос обновляется согласно последним Google Map необходимо.

ответ

-1

Вот обновленный код для Вашего вопроса:

package com.amal.googlemap; 

import java.io.IOException; 
import java.util.List; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 

import android.content.Context; 
import android.location.Address; 
import android.location.Geocoder; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.view.Menu; 
import android.widget.Toast; 

import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.GoogleMap.OnMapClickListener; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MainActivitytut extends FragmentActivity{ 

    GoogleMap googleMap; 
    MarkerOptions markerOptions; 
    LatLng latLng; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maintut); 

     SupportMapFragment supportMapFragment = (SupportMapFragment) 
       getSupportFragmentManager().findFragmentById(R.id.map); 

    // Getting a reference to the map 
      googleMap = supportMapFragment.getMap(); 

      // Setting a click event handler for the map 
      googleMap.setOnMapClickListener(new OnMapClickListener() { 

       @Override 
       public void onMapClick(LatLng arg0) {    

        // Getting the Latitude and Longitude of the touched location 
        latLng = arg0; 
        String lat = latLng.toString(); 
        Toast.makeText(getApplicationContext(), lat, 
          Toast.LENGTH_LONG).show(); 
        // Clears the previously touched position 
        googleMap.clear(); 

        // Animating to the touched position         
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));    

        // Creating a marker 
        markerOptions = new MarkerOptions(); 

        // Setting the position for the marker 
        markerOptions.position(latLng);      

        // Placing a marker on the touched position 
        googleMap.addMarker(markerOptions); 

        // Adding Marker on the touched location with address 
        new ReverseGeocodingTask(getBaseContext()).execute(latLng);    

       } 
      }); 


//  map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); 
//  if (map == null) { 
//   Toast.makeText(this, "Google Maps not available", 
//    Toast.LENGTH_LONG).show(); 
//    
//  } 


    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is 
     // present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 

    } 
// @Override 
// public boolean onOptionsItemSelected(MenuItem item) { 
// 
//  switch (item.getItemId()) { 
// 
//  case R.id.menu_sethybrid: 
//   map.setMapType(GoogleMap.MAP_TYPE_HYBRID); 
//   break; 
// 
//  case R.id.menu_showtraffic: 
//   map.setTrafficEnabled(true); 
//   break; 
// 
//  case R.id.menu_zoomin: 
//   map.animateCamera(CameraUpdateFactory.zoomIn()); 
//   break; 
// 
//  case R.id.menu_zoomout: 
//   map.animateCamera(CameraUpdateFactory.zoomOut()); 
//   break; 
// 
//  case R.id.menu_gotolocation: 
//   CameraPosition cameraPosition = new CameraPosition.Builder() 
//    .target(GOLDEN_GATE_BRIDGE) // Sets the center of the map to 
//           // Golden Gate Bridge 
//    .zoom(17)     // Sets the zoom 
//    .bearing(90) // Sets the orientation of the camera to east 
//    .tilt(30) // Sets the tilt of the camera to 30 degrees 
//    .build(); // Creates a CameraPosition from the builder 
//   map.animateCamera(CameraUpdateFactory.newCameraPosition(
//    cameraPosition)); 
//   break; 
// 
//  case R.id.menu_addmarker: 
//   // ---using the default marker--- 
//   /* 
//   map.addMarker(new MarkerOptions() 
//    .position(GOLDEN_GATE_BRIDGE) 
//    .title("Golden Gate Bridge") .snippet("San Francisco") 
//    .icon(BitmapDescriptorFactory 
//    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); 
//   */ 
// 
//   map.addMarker(new MarkerOptions() 
//    .position(GOLDEN_GATE_BRIDGE) 
//    .title("Golden Gate Bridge") 
//    .snippet("San Francisco") 
//    .icon(BitmapDescriptorFactory 
//    .fromResource(R.drawable.ic_launcher))); 
//   break; 
// 
//  case R.id.menu_getcurrentlocation: 
//   // ---get your current location and display a blue dot--- 
//   map.setMyLocationEnabled(true); 
// 
//   break; 
// 
//  case R.id.menu_showcurrentlocation: 
//   Location myLocation = map.getMyLocation(); 
//   LatLng myLatLng = new LatLng(myLocation.getLatitude(), 
//     myLocation.getLongitude()); 
// 
//   CameraPosition myPosition = new CameraPosition.Builder() 
//     .target(myLatLng).zoom(17).bearing(90).tilt(30).build(); 
//   map.animateCamera(
//    CameraUpdateFactory.newCameraPosition(myPosition)); 
//   break; 
//    
//  case R.id.menu_lineconnecttwopoints: 
//   //---add a marker at Apple--- 
//   map.addMarker(new MarkerOptions() 
//     .position(APPLE) 
//     .title("Apple") 
//     .snippet("Cupertino") 
//     .icon(BitmapDescriptorFactory.defaultMarker(
//        BitmapDescriptorFactory.HUE_AZURE))); 
// 
//   //---draw a line connecting Apple and Golden Gate Bridge--- 
//   map.addPolyline(new PolylineOptions() 
//    .add(GOLDEN_GATE_BRIDGE, APPLE).width(5).color(Color.RED)); 
//   break; 
//  } 
//  return true; 
// } 


    private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{ 
     Context mContext; 

     public ReverseGeocodingTask(Context context){ 
      super(); 
      mContext = context; 
     } 

     // Finding address using reverse geocoding 
     @Override 
     protected String doInBackground(LatLng... params) { 
      Geocoder geocoder = new Geocoder(mContext); 
      double latitude = params[0].latitude; 
      double longitude = params[0].longitude; 

      List<Address> addresses = null; 
      String addressText=""; 

      try { 
       addresses = geocoder.getFromLocation(latitude, longitude,1); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      if(addresses != null && addresses.size() > 0){ 
       Address address = addresses.get(0); 

       addressText = String.format("%s, %s, %s", 
         address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", 
         address.getLocality(),      
         address.getCountryName());    
      } 

      return addressText; 
     }  

     @Override 
     protected void onPostExecute(String addressText) { 
      // Setting the title for the marker. 
      // This will be displayed on taping the marker 
      markerOptions.title(addressText); 

      // Placing a marker on the touched position 
      googleMap.addMarker(markerOptions); 

     } 
    } 

} 
+0

Спасибо Android Android Я использовал это, но нет отображения lat и long. – Test123

+0

@Sonam: Вы очистили проект? Если нет, пожалуйста, очистите его ... Пожалуйста, проверьте мой код, который я поджарил для latlng. –

+0

Спасибо Это сделано, была некоторая ошибка с моей стороны .... – Test123

-1

Вы должны получить ключ подписи для приложения и API Google.

Следуйте инструкциям, чтобы ваши карты работали на this link.

Это учебник, в котором процесс подписи объясняется в this link.

Вы должны зарегистрировать отладку и производственный ключ для разработки и выпуска версии вашего приложения.

Смежные вопросы