2015-04-12 4 views
0

Я хотел бы нарисовать круг на карте, основанный на параметре, введенном пользователем.Участок круга на Картах Google V2, основанный на пользовательском вводе

Например, если пользователь вводит параметр радиуса 1000. Следующее, что произойдет, при нажатии кнопки «Сюжет» откроет Карты Google и нарисует на нем круг.

Я пробовал googled вокруг для связанных учебников. К сожалению, все учились нажимать на карту и автоматически рисовать фигуру, где радиус был определен в исходном и шахтном.

Ниже приводится моя часть кодов.

mapping.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="match_parent" 
    android:background="#607D8B"> 

    <TableRow 
     android:id="@+id/tableRow1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 

     <TextView 
      android:id="@+id/textView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Radius" 
      android:textAppearance="?android:attr/textAppearanceLarge" 
      android:layout_span="1" /> 

      <EditText 
       android:id="@+id/editText1" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:ems="10" 
       android:inputType="numberDecimal" 
       android:gravity="center"/> 
     <requestFocus /> 

    </TableRow> 



    <TableRow 
     android:id="@+id/tableRow4" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 

     <Button 
      android:id="@+id/button1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      style="?android:attr/buttonBarButtonStyle" 
      android:text="Clear" 
      android:layout_margin="10dp" 
      android:background="#37474F" 
      android:layout_column="0" /> 

     <Button 
      android:id="@+id/button2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentTop="true" 
      android:layout_toRightOf="@+id/button1" 
      style="?android:attr/buttonBarButtonStyle" 
      android:text="Plot" 
      android:layout_margin="10dp" 
      android:background="#37474F"/> 

    </TableRow> 

    <TableRow 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 

    </TableRow> 

</TableLayout> 

Это мой файл Java.

package com.epsilon.map; 

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class LossActivity extends Activity implements OnClickListener { 

    EditText radius = null; 
    Button plotButton = null; 
    Button clearButton = null; 

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

     radius = (EditText)findViewById(R.id.editText1);    
     plotButton = (Button)findViewById(R.id.button2); 
     plotButton.setOnClickListener(this); 
     clearButton = (Button)findViewById(R.id.button1); 
     clearButton.setOnClickListener(this); 
    } 

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

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     if(v == plotButton) { 
     double radius = Double.parseDouble(radius.getText().toString()); 
     Intent intent = new Intent(this,MapActivity.class); 
     //something to write overhere 
     intent.putExtra("radius",radius);// playing with this 
     this.startActivity(intent);      
     } 
     else if(v == clearButton) { 
      ((EditText)findViewById(R.id.editText1)).setText("");    
     } 
    } 

} 

Наконец является отображение активности карт Google, я думаю, что проблема у меня меньше представления о том, как связан файл Java выше, с другим Java файлом этого.

package com.epsilon.map; 

import android.graphics.Color; 
import android.location.Location; 
import android.location.LocationListener; 
import android.support.v7.app.ActionBarActivity; 
import android.support.v4.app.FragmentActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 

import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.Circle; 
import com.google.android.gms.maps.model.CircleOptions; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 


public class MapActivity extends FragmentActivity implements LocationListener{ 

    GoogleMap googleMap; 

    Marker marker; 
    Circle shape; 

    private double radius; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_map); 
     SupportMapFragment mfrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     googleMap = mfrag.getMap(); 

     googleMap.setMyLocationEnabled(true); 
     googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
    } 

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

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 
    private void setMarker(String locality, String country, double lat,double lng){ 

     LatLng LL = new LatLng(lat,lng); 
     MarkerOptions options = new MarkerOptions() 
       .title(locality) 
       .position(LL) 
       //.icon(BitmapDescriptor.fromResource(R.drawable.ic_mapmarker)) 
       .icon(BitmapDescriptorFactory.defaultMarker()); 

     marker = googleMap.addMarker(options); 

     shape = drawCircle(LL); 


    } 

    private Circle drawCircle(LatLng LL) { 

     CircleOptions options = new CircleOptions() 
       .center(LL) 
       .radius(radius) 
       .fillColor(0x330000FF) 
       .strokeColor(Color.BLUE) 
       .strokeWidth(3); 
     return googleMap.addCircle(options); 
    } 

    private void removeShape(){ 
     marker.remove(); 
     marker = null; 
     shape.remove(); 
     shape = null; 
    } 

} 

ответ

1

Итак, что вам нужно сделать, это что-то вроде этого:

В вашей LossActivity:

@Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     if(v == plotButton) { 
     double radius = Double.parseDouble(radius.getText().toString()); 
     Intent intent = new Intent(this, MapActivity.class); 
     //something to write overhere 
     Bundle b = new Bundle(); 
     b.putDouble("radius", radius); 
     intent.putExtras(b); 
     this.startActivity(intent);      
     } 
     else if(v == clearButton) { 
      ((EditText)findViewById(R.id.editText1)).setText("");    
     } 
    } 
    ..... 

, а затем в вашем MapActivity:

private String provider; 
private Location mCurrentLocation; 
private LocationManager locationManager; 
private double radius; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_map); 
     Bundle b = getIntent().getExtras(); 
     if (b != null) { 
      if (b.containsKey("radius")) { 
       radius = b.getDouble("radius"); 
      } 
     } 
     SupportMapFragment mfrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     googleMap = mfrag.getMap(); 

     googleMap.setMyLocationEnabled(true); 
     googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
     // Here starts the old code 
     //Criteria criteria = new Criteria(); 
     //provider = locationManager.getBestProvider(criteria, false); 
     //locationManager.requestLocationUpdates(provider, 5000, 5, this); 
     //mCurrentLocation = locationManager.getLastKnownLocation(provider); 
     //if (mCurrentLocation != null) { 
     //  onLocationChanged(mCurrentLocation); 
     //}   
    } 

    // Part of the new code 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     Criteria criteria = new Criteria(); 
     provider = locationManager.getBestProvider(criteria, false); 
     locationManager.requestLocationUpdates(provider, 500, 0, this); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
      setMarker("Locality", "Country", location.getLatitude(), location.getLongitude(); 
      locationManager.removeUpdates(this); 
    } 

Кроме того, включите GPS для лучшей точности.

+0

Я пробовал, но это не сработало – MkLim

+0

Есть ошибка или она просто не работает? – miselking

+0

Я ожидал при вводе радиуса при нажатии кнопки, предполагая, что он сначала должен определить мое местоположение, и как только это будет сделано, он начертит круг на карте – MkLim

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