[英]How to place marker on entered address in Google Maps?
字符串“ newAddress”來自用戶輸入地址的彈出窗口。 p1包含地址的緯度和經度。 放置標記時,標記沒有放置在正確的位置。 例如,當輸入墨爾本時,標記將放置在厄瓜多爾。 我的代碼有什么問題?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;
Button addNew;
Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
//BRINGS YOU TO THE POPUP SCREEN
addNew = (Button) findViewById(R.id.addNew);
addNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MapsActivity.this, AddLocationActivity.class);
MapsActivity.this.startActivity(intent);
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Intent intent = getIntent();
String newAddress = intent.getStringExtra("address");
//THIS IS WHAT HAPPENS WHEN NO ADDRESS IS ENTERED
if(newAddress == null||newAddress.matches("")) {Toast.makeText(context, "address is null", Toast.LENGTH_LONG).show();}
//THIS IS WHAT HAPPENS WHEN AN ADDRESS HAS BEEN ENETERED
else {Toast.makeText(context, newAddress, Toast.LENGTH_LONG).show();
Geocoder coder = new Geocoder(this);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(newAddress,5);
if (address==null) {
}
Address location=address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
//Turning the coordinates into a string
TextView coordtext = (TextView)findViewById(R.id.coorText);
coordtext.setText(onlyCoords);
double latValue = p1.latitude;
double longValue = p1.longitude;
// Add a marker to entered address and move the camera
LatLng newLocation = new LatLng(latValue, longValue);
mMap.addMarker(new MarkerOptions().position(newLocation).title(newAddress));
mMap.moveCamera(CameraUpdateFactory.newLatLng(newLocation));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我發現我不應該這樣做
p1 = new LatLng((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
我必須做
p1 = new LatLng((int) (location.getLatitude()),
(int) (location.getLongitude()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.