简体   繁体   中英

Add multiples markers from array

I'm new in coding and I'm trying to make my first app so I say sorry in advance if it could sound stupid to the most. My app should basically recollect datas (Edit Text) from the add client Activity and show markers in the map Activity. To do this I thought to put all the informations in Array and then show it on the map. The question is "how can I do that?" everything I do gives me lots of errors :/

This is where I'm stuck

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>

You should use Google Places API which has an auto complete adapter and predictions for places, below link shows a similar app. Google-Maps-Google-Places

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM