2016-03-17 34 views
0

字符串「newAddress」來自用戶輸入地址的彈出窗口。 p1包含地址的經度和緯度。 當標記被放置時,它不被放置在正確的位置。例如,當進入墨爾本時,標記被放置在厄瓜多爾。我的代碼有什麼問題?如何在Google地圖上的輸入地址上放置標記?

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(); 
     } 
    } 
} 
} 

回答

0

我發現我不應該做

p1 = new LatLng((int) (location.getLatitude() * 1E6), 
       (int) (location.getLongitude() * 1E6)); 

我不得不這樣做

p1 = new LatLng((int) (location.getLatitude()), 
       (int) (location.getLongitude())); 
相關問題