2013-10-10 2 views
0

안녕하세요 저는 Google지도에서 핀을 표시하고 끌어서 일부 소스 코드를 가져 오려고합니다. 이클립스로의 가져 오기가 성공했지만 내 장치에서지도를 실행할 수는 있지만 api key issue에 관한 것인가? 표시하기 위해 새로운 API 키를 생성해야합니까? 여기 android Google지도를 표시 할 수 없습니다

내가 가져했습니다 프로젝트이다 .. 사람이 도움이 붙어있어

second one

first one

도 여기에 두 번째 링크의 소스 코드입니다. 아이디어

에 대한

public class rescue extends MapActivity { 


private LocationManager myLocationManager; 
private LocationListener myLocationListener; 

private MapView myMapView; 
private MapController myMapController; 
private String provider; 
private MyLocationOverlay me=null; 


private int defaultLat =(int)(51.51216124955517); 
private int defaultLong =(int)(-0.1373291015625); 

private GeoPoint defaultGeoPint = new GeoPoint(defaultLat,defaultLong); 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.rescue); 

    setCurrentLocation(); 
    } 

@Override 
protected boolean isRouteDisplayed() { 
    // TODO Auto-generated method stub 
    return false; 
} 

private void setCurrentLocation() 
{ 
    myMapView = (MapView)findViewById(R.id.rescueMapView); 
    myMapView.setTraffic(true); 
    ///myMapView.setBuiltInZoomControls(true); 

    myMapController = myMapView.getController(); 
    myMapController.setZoom(16); //Fixed Zoom Level 

    myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    myLocationListener = new MyLocationListener(); 

    try 
    { 
    Criteria criteria = new Criteria(); 
    provider = myLocationManager.getBestProvider(criteria, false); 

    Location location = myLocationManager.getLastKnownLocation(provider); 

    myLocationManager.requestLocationUpdates(
      provider, 
    0, 
    0, 
    myLocationListener); 

    Location lastLocation = myLocationManager.getLastKnownLocation(provider); 

     if(lastLocation != null) 
     { 
      int lastLocLat =(int)(lastLocation.getLatitude()*1000000); 
      int lastLocLong =(int)(lastLocation.getLongitude()*1000000); 
      //Get the current location in start-up 
      GeoPoint initGeoPoint = new GeoPoint(lastLocLat,lastLocLong); 
      CenterLocatio(initGeoPoint); 
     } 
     else 
     { 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setTitle("Location Services Disabled") 
       .setMessage("The location service on the device are disabled, your location is not able to be found, please call AXA uding the button below to be rescued") 
       .setCancelable(false) 
       .setPositiveButton("Drop pin", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
          //do things 
         CenterLocatio(defaultGeoPint); 
        } 
       }); 
      builder.create().show(); 
     } 
    } 
    catch (Exception e) 
    { 
    // TODO: handle exception 


     Context context = getApplicationContext(); 
     String toasttext = e.getMessage(); 
     int duration = Toast.LENGTH_SHORT; 

     Toast toast = Toast.makeText(context, toasttext, duration); 
     toast.show(); 
    } 
} 

private void CenterLocatio(GeoPoint centerGeoPoint) 
{ 
    myMapView.getOverlays().clear(); 
    myMapController.animateTo(centerGeoPoint); 
    Drawable marker=getResources().getDrawable(R.drawable.marker); 

    marker.setBounds(0, 0, marker.getIntrinsicWidth(), 
          marker.getIntrinsicHeight()); 

    int lat = centerGeoPoint.getLatitudeE6(); 
    int lon = centerGeoPoint.getLongitudeE6(); 

    double lat1 = centerGeoPoint.getLatitudeE6()/1E6; 

    double lon1 = centerGeoPoint.getLongitudeE6()/1E6; 

    ArrayList<Double> passing = new ArrayList<Double>(); 
    passing.add(lat1); 
    passing.add(lon1); 

    Context context = getApplicationContext(); 
    ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask(); 
    task.applicationContext = context; 
    task.activityContext = rescue.this; 
    task.execute(passing); 

    myMapView.getOverlays().add(new SitesOverlay(marker,lat, lon)); 

    me=new MyLocationOverlay(this, myMapView); 
    myMapView.getOverlays().add(me); 

}; 

private class MyLocationListener implements LocationListener{ 

    @Override 
     public void onLocationChanged(Location argLocation) { 
     // TODO Auto-generated method stub 
     GeoPoint myGeoPoint = new GeoPoint(
     (int)(argLocation.getLatitude()*1000000), 
     (int)(argLocation.getLongitude()*1000000)); 

     //CenterLocatio(myGeoPoint); 
     } 

     public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 
     } 

     public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 
     } 

     public void onStatusChanged(String provider, 
     int status, Bundle extras) { 
     // TODO Auto-generated method stub 
     } 
    } 


private GeoPoint getPoint(int lat, int lon) { 

    return(new GeoPoint(lat, lon)); 

    /* 
     return(new GeoPoint((int)(lat*1000000.0), 
           (int)(lon*1000000.0))); 
          */ 
     } 
    private class SitesOverlay extends ItemizedOverlay<OverlayItem> { 
     private List<OverlayItem> items=new ArrayList<OverlayItem>(); 
     private Drawable marker=null; 
     private OverlayItem inDrag=null; 
     private ImageView dragImage=null; 
     private int xDragImageOffset=0; 
     private int yDragImageOffset=0; 
     private int xDragTouchOffset=0; 
     private int yDragTouchOffset=0; 

     public SitesOverlay(Drawable marker, int lat, int longitude) { 
      super(marker); 
      this.marker=marker; 

      dragImage=(ImageView)findViewById(R.id.drag); 
      xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2; 
      yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight(); 

      items.add(new OverlayItem(getPoint(lat, 
               longitude), 
            "UN", "United Nations")); 

      /* 
      items.add(new OverlayItem(getPoint(40.76866299974387, 
               -73.98268461227417), 
            "Lincoln Center", 
            "Home of Jazz at Lincoln Center")); 
      */ 
      populate(); 
     } 

     @Override 
     protected OverlayItem createItem(int i) { 
      return(items.get(i)); 
     } 

     @Override 
     public void draw(Canvas canvas, MapView mapView, 
          boolean shadow) { 
      super.draw(canvas, mapView, shadow); 

      boundCenterBottom(marker); 
     } 

     @Override 
     public int size() { 
      return(items.size()); 
     } 

     @Override 
     public boolean onTouchEvent(MotionEvent event, MapView mapView) { 
      final int action=event.getAction(); 
      final int x=(int)event.getX(); 
      final int y=(int)event.getY(); 
      boolean result=false; 

      if (action==MotionEvent.ACTION_DOWN) { 
      for (OverlayItem item : items) { 
       Point p=new Point(0,0); 

       myMapView.getProjection().toPixels(item.getPoint(), p); 

       if (hitTest(item, marker, x-p.x, y-p.y)) { 
       result=true; 
       inDrag=item; 
       items.remove(inDrag); 
       populate(); 

       xDragTouchOffset=0; 
       yDragTouchOffset=0; 

       setDragImagePosition(p.x, p.y); 
       dragImage.setVisibility(View.VISIBLE); 

       xDragTouchOffset=x-p.x; 
       yDragTouchOffset=y-p.y; 

       break; 
       } 
      } 
      } 
      else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) { 
      setDragImagePosition(x, y); 
      result=true; 
      } 
      else if (action==MotionEvent.ACTION_UP && inDrag!=null) { 
      dragImage.setVisibility(View.GONE); 

      GeoPoint pt=myMapView.getProjection().fromPixels(x-xDragTouchOffset, 
                 y-yDragTouchOffset); 


      String title = inDrag.getTitle(); 
      OverlayItem toDrop=new OverlayItem(pt, title, 
               inDrag.getSnippet()); 

      items.add(toDrop); 
      populate(); 
      double lat = pt.getLatitudeE6()/1E6; 

      double lon = pt.getLongitudeE6()/1E6; 

      ArrayList<Double> passing = new ArrayList<Double>(); 
      passing.add(lat); 
      passing.add(lon); 

      Context context = getApplicationContext(); 
      ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask(); 
      task.applicationContext = context; 
      task.activityContext = rescue.this; 
      task.execute(passing); 

      //CenterLocatio(pt); 
      inDrag=null; 
      result=true; 
      } 

      return(result || super.onTouchEvent(event, mapView)); 
     } 

     private void setDragImagePosition(int x, int y) { 
      RelativeLayout.LayoutParams lp= 
      (RelativeLayout.LayoutParams)dragImage.getLayoutParams(); 

      lp.setMargins(x-xDragImageOffset-xDragTouchOffset, 
          y-yDragImageOffset-yDragTouchOffset, 0, 0); 
      dragImage.setLayoutParams(lp); 
     } 
     } 

    public class ReverseGeocodeLookupTask extends AsyncTask <ArrayList<Double>, Void, String> 
    { 
     private ProgressDialog dialog; 
     protected Context applicationContext; 
     protected Context activityContext; 

     @Override 
     protected void onPreExecute() 
     { 
      this.dialog = ProgressDialog.show(activityContext, "Please wait", 
        "Requesting location", true); 
     } 


     protected String doInBackground(ArrayList<Double>... params) 
     { 


      String foundAddress = ""; 
      String localityName = ""; 
      ArrayList<Double> passed = params[0]; 
      double lat = passed.get(0); 
      double lon = passed.get(1); 
      try 
      { 

      List<Address> addresses = new Geocoder(applicationContext,Locale.getDefault()).getFromLocation(lat,lon, 1); 
      if (addresses.size() > 0) 
      { 
       String addressLine = ""; 

       for(Integer i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++) 
       { 
        if(!addressLine.equals("")) 
        { 
         addressLine+= ", "; 
        } 

        addressLine+= addresses.get(0).getAddressLine(i); 
       } 

       if(addressLine!="") 
       { 
        foundAddress+= addressLine; 
       } 
      } 
      } 
      catch (Exception e) { 
      } 
      finally 
      { 
      } 
      return foundAddress; 
     } 

     @Override 
     protected void onPostExecute(String result) 
     { 
      this.dialog.cancel(); 
      showToast(result); 

     } 
    } 

    public void showToast(String message) 
    { 
     Context context = getApplicationContext(); 
     String toasttext = message; 
     int duration = Toast.LENGTH_SHORT; 

     Toast toast = Toast.makeText(context, toasttext, duration); 
     toast.show(); 
    } 
     } 

덕분에 여기 레이아웃 XML 먼저 자신의 키를 생성해야

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" android:layout_height="fill_parent" 
android:orientation="vertical" android:id="@+id/rescue_rel_layout" 
android:gravity="top" android:background="#fff"> 
<RelativeLayout android:layout_width="fill_parent" 
    android:layout_height="45dp" android:id="@+id/rescue_top_control_bar" 
    android:background="#FFFFFF" android:gravity="center_vertical"> 



    <TextView android:id="@+id/rescueText" 
     android:layout_width="wrap_content" 
     android:layout_height="55dp" 
     android:text="Where are you ?" 
     android:gravity="center_vertical|center_horizontal" 
     android:textSize="20dp" 
     android:textStyle="bold" 
     android:textColor="#1D0073" 
     android:layout_weight="1.0" 
     android:layout_centerInParent="true" 
    /> 



</RelativeLayout> 



<LinearLayout android:id="@+id/LinearLayout01" 
    android:layout_width="fill_parent" android:layout_height="fill_parent" 
    android:layout_below="@id/rescue_top_control_bar" 

    android:orientation="vertical"> 





    <RelativeLayout  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#ff0000" 
    > 

     <RelativeLayout  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#ff0000" 
    android:layout_weight="1" 
    > 

      <RelativeLayout  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#ff0000" 
    android:layout_weight="1" 
    >  

    <com.google.android.maps.MapView 

      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:foregroundGravity="top" 
      android:apiKey="" 
      android:clickable="true" 
      android:layout_weight="1" 
      android:id="@+id/rescueMapView" 
      /> 

    <ImageView android:id="@+id/drag" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/marker_up" 
     android:visibility="gone" 
     /> 


    </RelativeLayout> 

    <LinearLayout 
     android:id="@+id/loader" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:background="#000" 
     android:layout_alignParentBottom="true" 
     android:visibility="invisible" 
     > 



     </LinearLayout>   

    </RelativeLayout> 




    </RelativeLayout>  


</LinearLayout> 

+0

오류가 있습니까? 관련 코드 만 게시하십시오. – GrIsHu

+0

위의 코드는 내가 사용하고있는 코드입니다 .. 다른 오류는 없습니다 ..지도 자체를 제외하고 모두 표시됩니다. – regeme

+0

유형 안전 : ArrayList 의 일반적인 배열이 varargs 매개 변수에 대해 만들어집니다. 로컬 변수 위치는 읽히지 않습니다. 로컬 변수 myGeoPoint는 읽히지 않습니다. 지역 변수 localityName은 읽히지 않습니다 .. 이것들은 내가 얻는 경고입니다 .. – regeme

답변

2

에게 있습니다. 또한 따라야 할 다른 설정이 있습니다. 여기에 좋은 toutorial-입니다>Google map v2

이 편집 내가 제안 :

레이아웃 XML 내부

사용 (즉 toutorial에 4.5th 단계를 activity_main.xml.)

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 


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


</RelativeLayout> 

메인 클래스를 작성하여 'FragmentActivity'를 확장하십시오 (튜토리얼에서 4.6 번째 단계)

public class MainActivity extends FragmentActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main);// This line is all that you need to display a map. 

    } 
    } 

마지막으로 중요한 것은 AndroidManifest.xml입니다.

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="your_package" 
    android:versionCode="1" 
    android:versionName="1.0" > 


<permission 
    android:name="your_package.permission.MAPS_RECEIVE" 
    android:protectionLevel="signature" /> 

<uses-permission android:name="your_package.permission.MAPS_RECEIVE" /> 

<uses-sdk 
    android:minSdkVersion="12" 
    android:targetSdkVersion="17" /> 

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

<!-- Required to show current location --> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

<!-- Required OpenGL ES 2.0. for Maps V2 --> 
<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name"> 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:theme="@style/AppBaseTheme"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <!-- Goolge API Key --> 
    <meta-data 
     android:name="com.google.android.maps.v2.API_KEY" 
     android:value="your_api_key" /> 
</application> 


</manifest> 
+0

어이 이슈가 계속됩니다 .. 여기까지 모든 단계를 완료했습니다. 알고있는 한 멀리 시장에 앱을 게시 할 때 우리는 우리 고유의 키. 여기서 우리는 debug.keystore를 사용하고 콘솔에서 새 API 키를 생성 한 다음 매니페스트 파일에 추가했지만 여전히 동일한 파일을 추가합니다. – regeme

+0

현재 프로젝트를 복구하는 대신 새 프로젝트를 만듭니다. 그 전에는 2 가지 더 제안 해 드리겠습니다. – Nizam

+0

방향이 지정되지 않고 기본값은 가로입니다. 이는 자식 이 동적으로 추가 될 때 일반적인 버그 소스입니다. 이것은 android : name = "com.google.android.gms.maps.SupportMapFragment"를 추가하려고 시도 할 때 발생하는 오류입니다. 레이아웃 xml에 어디에서 추가해야합니까? 현재이 태그 ( regeme

0

콘솔에서 Google Maps Android API v2를 사용 설정 했습니까? 많은 사람들이 그것을 돌리는 것을 잊어 버린다. 왼쪽의 서비스를 선택하고 Google지도를 켜십시오. Android API v2

+0

절대적으로 ..... – regeme

관련 문제