Google地图标记使用标记自动填充地址

时间:2016-11-01 10:56:29

标签: java android google-maps

我想用谷歌地图标记标记我的地址(编辑文本)。

我创建了一个简单的表单,但是当我填充地址并在同一个地方放一个标记时,我想在地图上标记它。

我正在获取地址字段的纬度和经度然后我会使用标记来固定它但我在初始阶段只有问题(请考虑我作为Android中的菜鸟,因为我已经开始几天了)

注册活动

    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.SeekBar;
    import android.widget.SeekBar.OnSeekBarChangeListener;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
    import com.google.android.gms.maps.GoogleMap.OnInfoWindowCloseListener;
    import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
    import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.IOException;
    import java.io.InputStream;

    import butterknife.Bind;
    import butterknife.ButterKnife;

    public class SignupActivity extends FragmentActivity implements OnMarkerClickListener, OnMarkerDragListener, OnInfoWindowClickListener, OnMapReadyCallback, OnInfoWindowCloseListener, GoogleMap.OnInfoWindowLongClickListener, OnSeekBarChangeListener {

        private static final String TAG = "SignupActivity";
        private GoogleMap googleMap;
        private static LatLng goodLatLng = new LatLng(37, -120);
        LatLng addressPos;
        Marker addressMarker;

        @Bind(R.id.input_name)
        EditText _nameText;
        @Bind(R.id.input_address)
        EditText _addressText;
        @Bind(R.id.input_email)
        EditText _emailText;
        @Bind(R.id.input_mobile)
        EditText _mobileText;
        @Bind(R.id.input_password)
        EditText _passwordText;
        @Bind(R.id.input_reEnterPassword)
        EditText _reEnterPasswordText;
        @Bind(R.id.btn_signup)
        Button _signupButton;
        @Bind(R.id.link_login)
        TextView _loginLink;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_signup);
            ButterKnife.bind(this);

            String address = _addressText.getText().toString();        

            // Initial Map
            try {

                if (googleMap == null) {
                    MapFragment mapFragment = (MapFragment) getFragmentManager()
                            .findFragmentById(R.id.map);
                    mapFragment.getMapAsync(this);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }       

            _signupButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    signup();
                }
            });

            _loginLink.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Finish the registration screen and return to the Login activity
                    Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
                    startActivity(intent);
                    finish();
                    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                }
            });        
        }       

        public void signup() {
            Log.d(TAG, "Signup");

            if (!validate()) {
                onSignupFailed();
                return;
            }

            _signupButton.setEnabled(false);

            final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
                    R.style.AppTheme_Dark_Dialog);
            progressDialog.setIndeterminate(true);
            progressDialog.setMessage("Creating Account...");
            progressDialog.show();

            String name = _nameText.getText().toString();
            String address = _addressText.getText().toString();
            String email = _emailText.getText().toString();
            String mobile = _mobileText.getText().toString();
            String password = _passwordText.getText().toString();
            String reEnterPassword = _reEnterPasswordText.getText().toString();

            // TODO: Implement your own signup logic here.

            new android.os.Handler().postDelayed(
                    new Runnable() {
                        public void run() {
                            // On complete call either onSignupSuccess or onSignupFailed
                            // depending on success
                            onSignupSuccess();
                            // onSignupFailed();
                            progressDialog.dismiss();
                        }
                    }, 3000);
        }

        public void onSignupSuccess() {
            _signupButton.setEnabled(true);
            setResult(RESULT_OK, null);
            finish();
        }

        public void onSignupFailed() {
            Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

            _signupButton.setEnabled(true);
        }

        public boolean validate() {
            boolean valid = true;

            String name = _nameText.getText().toString();
            String address = _addressText.getText().toString();
            String email = _emailText.getText().toString();
            String mobile = _mobileText.getText().toString();
            String password = _passwordText.getText().toString();
            String reEnterPassword = _reEnterPasswordText.getText().toString();

            if (name.isEmpty() || name.length() < 3) {
                _nameText.setError("at least 3 characters");
                valid = false;
            } else {
                _nameText.setError(null);
            }

            if (address.isEmpty()) {
                _addressText.setError("Enter Valid Address");
                valid = false;
            } else {
                _addressText.setError(null);
            }

            if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                _emailText.setError("enter a valid email address");
                valid = false;
            } else {
                _emailText.setError(null);
            }

            if (mobile.isEmpty() || mobile.length()!=10) {
                _mobileText.setError("Enter Valid Mobile Number");
                valid = false;
            } else {
                _mobileText.setError(null);
            }

            if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
                _passwordText.setError("between 4 and 10 alphanumeric characters");
                valid = false;
            } else {
                _passwordText.setError(null);
            }

            if (reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))) {
                _reEnterPasswordText.setError("Password Do not match");
                valid = false;
            } else {
                _reEnterPasswordText.setError(null);
            }

            return valid;
        }

        @Override
        public boolean onMarkerClick(Marker marker) {
            return false;
        }

        @Override
        public void onMarkerDragStart(Marker marker) {        
        }

        @Override
        public void onMarkerDrag(Marker marker) {        
        }

        @Override
        public void onMarkerDragEnd(Marker marker) {        
        }

        @Override
        public void onInfoWindowClick(Marker marker) {        
        }

        @Override
        public void onMapReady(GoogleMap Map) {
            googleMap=Map;
            googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            // Put a dot on my current location
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            googleMap.setMyLocationEnabled(true);
            googleMap.setIndoorEnabled(true);
            googleMap.setTrafficEnabled(true);
            // 3D building
            googleMap.setBuildingsEnabled(true);
            // Get zoom button
            googleMap.getUiSettings().setZoomControlsEnabled(true);

            Marker marker = googleMap.addMarker(new MarkerOptions()
                    .position(goodLatLng)
                    .title("Address"));        
        }

        public void showAddressMarker(View view) {

            String newAddress = _addressText.getText().toString();

            if (newAddress != null) {
                new PlaceAMarker().execute(newAddress);
            }
        }
        class PlaceAMarker extends AsyncTask<String, String, String> {

            @Override
            protected String doInBackground(String... params) {
                String startAddress = params[0];
                startAddress = startAddress.replaceAll(" ", "%20");

                getLatLng(startAddress, false);

                return null;
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);

                addressMarker = googleMap.addMarker(new MarkerOptions()
                        .position(addressPos).title("Address"));
            }
        }
        protected void getLatLng(String address, boolean setDestination) {
            String uri = "http://maps.google.com/maps/api/geocode/json?address="
                    + address + "&sensor=false";

            HttpGet httpGet = new HttpGet(uri);

            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();

            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();

                InputStream stream = entity.getContent();

                int byteData;
                while ((byteData = stream.read()) != -1) {
                    stringBuilder.append((char) byteData);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            double lat = 0.0, lng = 0.0;

            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(stringBuilder.toString());
                lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                        .getJSONObject("geometry").getJSONObject("location")
                        .getDouble("lng");
                lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                        .getJSONObject("geometry").getJSONObject("location")
                        .getDouble("lat");

            } catch (JSONException e) {
                e.printStackTrace();
            }
               addressPos = new LatLng(lat, lng);        
        }

        @Override
        public void onInfoWindowClose(Marker marker) {        
        }

        @Override
        public void onInfoWindowLongClick(Marker marker) {        
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {        
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {        
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {        
        }
    }

主要活动文件

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;

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

    public class MainActivity extends ActionBarActivity {
        private GoogleMap googleMap;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }   

        @Override
        protected void onResume() {
            super.onResume();        
        }

        @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_main, 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);
        }
    }

注册xml

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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="56dp"
        android:paddingLeft="24dp"
        android:paddingRight="24dp">

        <ImageView android:src="@drawable/logo"
            android:layout_width="wrap_content"
            android:layout_height="72dp"
            android:layout_marginBottom="24dp"
            android:layout_gravity="center_horizontal" />

        <!-- Name Label -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">
            <EditText android:id="@+id/input_name"
                style="@style/TextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:hint="Name" />
        </android.support.design.widget.TextInputLayout>

        <!-- Address Label -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">
            <fragment
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:id="@+id/map"
                android:name="com.google.android.gms.maps.MapFragment" />
            <EditText android:id="@+id/input_address"
                style="@style/TextLabel"
                android:layout_marginTop="23dp"
                android:layout_marginRight="10dp"
                android:layout_marginLeft="10dp"
                android:ems="10"
                android:layout_below="@+id/map"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPostalAddress"
                android:hint="Address" />

        </android.support.design.widget.TextInputLayout>

        <!--  Email Label -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">
            <EditText android:id="@+id/input_email"
                style="@style/TextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:hint="Email" />
        </android.support.design.widget.TextInputLayout>

        <!-- mobile number -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">
            <EditText android:id="@+id/input_mobile"
                style="@style/TextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:hint="Mobile Number" />
        </android.support.design.widget.TextInputLayout>

        <!-- Password Label -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">
            <EditText android:id="@+id/input_password"
                style="@style/TextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Password"/>
        </android.support.design.widget.TextInputLayout>

        <!-- Password Re-enter Label -->
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">
            <EditText android:id="@+id/input_reEnterPassword"
                style="@style/TextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Re-enter Password"/>
        </android.support.design.widget.TextInputLayout>

        <!-- Signup Button -->
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_signup"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:layout_marginBottom="24dp"
            android:padding="12dp"
            android:text="Create Account"/>

        <TextView android:id="@+id/link_login"
            style="@style/TextView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="24dp"
            android:text="Already a member? Login"
            android:gravity="center"
            android:textSize="16dip"/>

    </LinearLayout>
</ScrollView>

这是我在运行时得到的错误nad请明确说明事情,因为我是android的新手并且热衷于快速学习。

错误记录

AndroidRuntime: FATAL EXCEPTION: main Process: package, PID: 6547 java.lang.RuntimeException: Unable to start activity ComponentInfo{package.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2519) at android.app.ActivityThread.access$800(ActivityThread.java:162) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:189) at android.app.ActivityThread.main(ActivityThread.java:5532) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment and so on.

0 个答案:

没有答案