web-dev-qa-db-ja.com

Android、メソッドgetMap()を解決できません

このコードに問題があります。「メソッドgetMap()を解決できません。問題のある場所が見つかりません。コードのヘルプが必要です。Android Studioを使用し、mySQLのマーカーの場所を取得する必要があります。 Jsonと。

    googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();`

そして、ここに完全なコードがあります

 public class MainActivity extends FragmentActivity {

    private GoogleMap googleMap;
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;
    private GoogleApiClient client2;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "http://www.evil.cl/getLatLon.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for (int i = 0; i < data.length(); i++) {
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                location.add(map);

            }

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

        googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();

        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
            googleMap.addMarker(marker);
        }

        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    @Override
    public void onStart() {
        super.onStart();
        client2.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW,
                "Main Page", 


                Uri.parse("http://Host/path"),

                Uri.parse("Android-app://com.example.hector.prueba1/http/Host/path")
        );
        AppIndex.AppIndexApi.start(client2, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW,
                "Main Page", 
                Uri.parse("http://Host/path"),
                Uri.parse("Android-app://com.example.hector.prueba1/http/Host/path")
        );
        AppIndex.AppIndexApi.end(client2, viewAction);
        client2.disconnect();
    }
}

getMap()メソッドは廃止されましたが、play-services 9.2の更新後に削除されたため、getMapAsync()を使用することをお勧めします。アプリのplay-servicesを9.2に更新したくない場合にのみ、getMap()を引き続き使用できます。

GetMapAsync()を使用するには、アクティビティまたはフラグメントにOnMapReadyCallbackインターフェースを実装します。

public class Fragment_Map extends Android.support.v4.app.Fragment
      implements OnMapReadyCallback { }

次に、マップの初期化中に、getMap()の代わりにgetMapAsync()を使用します。

 private void initializeMap() {
  if (mMap == null) {
    SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
    mapFrag.getMapAsync(this);
  }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    setUpMap();
}
21
Karun Shrestha

getMapは非推奨です。以下のgetMapAsyncを使用してください。

これをgoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();に、このgoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMapAsync();に変更します。

pDate:

このように使用し、

package your.app.name;

import Android.app.Activity;
import Android.os.Bundle;
import Android.view.Menu;
import Android.view.MenuItem;

import com.google.Android.gms.maps.GoogleMap;
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.MarkerOptions;

public class MainActivity extends Activity implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.addMarker(new MarkerOptions()
                .position(new LatLng(0, 0))
                .title("Marker"));
    }

    //onCreateOptionsMenu: no changes    
    //onOptionsItemSelected: no changes
}
6

Jsonの読み込みに問題があります。「getMap」は非推奨になり、グーグルはgetMap()を使用する必要があると述べました。どうすれば問題を解決できますか?

これはあなたがコードを持っています

        try {
        JSONArray innerJsonArray = json_array.getJSONArray(0);
        JSONObject json = innerJsonArray.getJSONObject(0);
        MapFragment mapFrag = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
        GeoJsonLayer layer = new GeoJsonLayer(mapFrag.getMap() , json);
        layer.addLayerToMap();

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

完全なコード:

 public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        //JSONArray json = new JSONObject();
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        String url = "https://www.oxidocs.com/ind/modelo/test.php";

        JSONArray user = null;

        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONArray json_array = jParser.getJSONFromUrl(url);


        try {
            JSONArray innerJsonArray = json_array.getJSONArray(0);
            JSONObject json = innerJsonArray.getJSONObject(0);
            MapFragment mapFrag = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
            GeoJsonLayer layer = new GeoJsonLayer(mapFrag.getMap() , json);
            layer.addLayerToMap();

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

}
public class MapPane extends FragmentActivity implements OnMapReadyCallback {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_activity);

    SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.safety_map));
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap map) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
 map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        map.setMyLocationEnabled(true);
        map.setTrafficEnabled(true);
        map.setIndoorEnabled(true);
        map.setBuildingsEnabled(true);
        map.getUiSettings().setZoomControlsEnabled(true);
    }
}

それは完全に動作します。ありがとう。

0
omor