java - 从数组中添加多个标记

标签 java android

我是编码新手,我正在尝试制作我的第一个应用程序,所以如果这听起来很愚蠢,我提前说声抱歉。 我的应用程序基本上应该从添加客户端 Activity 中重新收集数据(编辑文本)并在 map Activity 中显示标记。 为此,我想将所有信息放入数组中,然后将其显示在 map 上。 问题是“我怎样才能做到这一点?”我所做的一切都会给我带来很多错误:/

这就是我被困住的地方

MapsActivity.java

public class  MapsActivity extends FragmentActivity implements
        OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener
{

    private GoogleMap mMap;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;
    private Location lastLocation;
    private static final int Request_User_Location_Code = 99;
    private Button button;




    public MapsActivity() {
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
        checkUserlLocationPermission();
        }
                // 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);

            //set onclicklistener on the button
        button = (Button) findViewById(R.id.btnAddClient);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                Intent intent =new Intent(MapsActivity.this,AddClient.class);
                startActivity(intent);
            }
        });
    }



    @Override
    public void onMapReady(GoogleMap googleMap)


    {
        mMap = googleMap;

                //Asking for permission and set current location
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

    }
        //Checking permission
    private boolean checkUserlLocationPermission()
    {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
            {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
            }
            else
            {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
            }
            return false;
        }
        else
        {
            return true;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        switch (requestCode)
        {
            case Request_User_Location_Code:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    {
                        if (googleApiClient == null)
                        {
                            buildGoogleApiClient();
                        }
                        mMap.setBuildingsEnabled(true);
                    }
                }
                else
                {
                    Toast.makeText(this,"DENIED", Toast.LENGTH_SHORT).show();

                }
                return;
        }
    }

    protected synchronized void buildGoogleApiClient()
    {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        googleApiClient.connect();

    }

    @Override
    public void onLocationChanged(Location location)
    {

        lastLocation = location;

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
        CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
        mMap.moveCamera(center);
        mMap.animateCamera(zoom);

        if (googleApiClient != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);

        }
    }

    //Set interval location
    @Override
    public void onConnected(@Nullable Bundle bundle)
    {
        locationRequest = new LocationRequest();
        locationRequest.setInterval(1100);
        locationRequest.setFastestInterval(1100);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

activity_map.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".MapsActivity" >



    <Button
        android:id="@+id/btnAddClient"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="20dp"
        android:background="@drawable/mybutton"
        android:text="Add client"
        />

</fragment>

AddClient.java

public class AddClient extends AppCompatActivity {

    public Button btnDone;
    public EditText name;
    public EditText address;
    public LatLng latLng;
    public GoogleMap mMap;
    public Marker marker;

    ArrayList<String> clientNames = new ArrayList<>();
    ArrayList<String> clientAddress = new ArrayList<>();

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

        btnDone = (Button) findViewById(R.id.done_button);
        name = (EditText) findViewById(R.id.edit_name);
        btnDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                clientNames.add(name.getText().toString());
                clientAddress.add(address.getText().toString());
                getLocationFromAddress();
            }

            public void getLocationFromAddress(String strAddress) {
                //Create coder with Activity context - this
                Geocoder coder = new Geocoder(this);
                List<Address> address;

                try {
                    //Get latLng from String
                    address = coder.getFromLocationName(strAddress, 5);

                    //check for null
                    if (address == null) {
                        return;
                    }

                    //Lets take first possibility from the all possibilities.
                    Address location = address.get(0);
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                    //Put marker on map on that LatLng
                    Marker srchMarker = mMap.addMarker(new MarkerOptions().position(latLng).title("name"));

                    //Animate and Zoon on that map location
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}

addclient.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginBottom="25dip"
        android:text="NEW CLIENT DETAILS"
        android:textStyle="bold"
        android:textSize="30dp"
        android:gravity="center_horizontal"/>


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Client name:"
        android:textSize="20dp"/>
<EditText
    android:id="@+id/edit_name"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:text=""
    />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:text="Client address"
        android:textSize="20dp"/>
<EditText
    android:id="@+id/edit_lastname"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:text=""
    />
<Button
    android:id="@+id/done_button"
    android:layout_height="wrap_content"
    android:text="DONE"
    android:layout_width="130dip"
    android:background="@drawable/mybutton"
    android:layout_gravity="center"
    />

</LinearLayout>

最佳答案

您应该使用 Google Places API,它具有自动完成适配器和地点预测功能,下面的链接显示了类似的应用程序。 Google-Maps-Google-Places

关于java - 从数组中添加多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59057272/

相关文章:

java - Android 获取固定选项卡、PageViewer 来加载不同的 fragment

android - 具有任意数量行类型的 ListView 适配器(不知道不同行类型的数量)

java - 检索数据重复错误

java - Android Web 服务客户端 (JSON)

android - 重用膨胀 View

java - 将 Json 转换为特定的类

android - 如何验证android中的编辑文本,使其最多包含6位和小数点后2位?

java - java中如何向匿名类传递信息?

java - 将 Jersey 服务实例发布到 Grizzly

java - maven:包括单个 jar 的选定依赖项