有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带地址字段的java Google地图标记

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

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

我得到地址字段的经度和经度,然后我用一个记号来标记它,但是我只在初始阶段有问题(请考虑我作为Android的NOOB,因为我已经开始几天了)

报名活动

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

import com.google.安卓.gms.maps.GoogleMap;
import com.google.安卓.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.安卓.gms.maps.GoogleMap.OnInfoWindowCloseListener;
import com.google.安卓.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.安卓.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.安卓.gms.maps.MapFragment;
import com.google.安卓.gms.maps.OnMapReadyCallback;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.gms.maps.model.Marker;
import com.google.安卓.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 安卓.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() || !安卓.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, 安卓.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 安卓.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 安卓.content.Intent;
import 安卓.os.Bundle;
import 安卓.support.v7.app.ActionBarActivity;
import 安卓.view.Menu;
import 安卓.view.MenuItem;

import com.google.安卓.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:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:layout_width="fill_parent"
    安卓:layout_height="fill_parent"
    安卓:fitsSystemWindows="true">

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

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

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

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

        </安卓.support.design.widget.TextInputLayout>



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


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

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

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

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

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

    </LinearLayout>
</ScrollView>

AndroidRuntime:致命异常:main 工艺:包装,PID:6547 JAVAlang.RuntimeException:无法启动活动组件信息{package.MainActivity}:安卓。看法膨胀异常:二进制XML文件行#13:膨胀类片段时出错 在安卓。应用程序。活动线程。performLaunchActivity(ActivityThread.java:2455) 在安卓。应用程序。活动线程。handleLaunchActivity(ActivityThread.java:2519) 在安卓。应用程序。活动线程。访问$800(ActivityThread.java:162) 在安卓。应用程序。ActivityThread$H.handleMessage(ActivityThread.java:1412) 在安卓。操作系统。汉德勒。dispatchMessage(Handler.java:106) 在安卓。操作系统。活套。loop(Looper.java:189) 在安卓。应用程序。活动线程。main(ActivityThread.java:5532) 在爪哇。朗,反思一下。方法调用(本机方法) 在爪哇。朗,反思一下。方法调用(Method.java:372) 在com上。安卓内部的操作系统。ZygoteInit$MethodandArgscaler。run(zyteinit.java:950) 在com上。安卓内部的操作系统。合子体。main(ZygoteInit.java:745) 原因:安卓。看法膨胀异常:二进制XML文件行#13:膨胀类片段时出错


共 (2) 个答案

  1. # 1 楼答案

    <?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>
        <fragment
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.MapFragment" />
        <!  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">
    
            <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>
    

    请更改xml代码并重试

  2. # 2 楼答案

    mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                   addMarker(latLng);
                }
            });
    
    
    private void addMarker(LatLng latLng){
    String text=editText.getText().toString();
    Marker marker = mGoogleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title(text));
    }
    

    简单的方法。进行定制