繁体   English   中英

初始化Google Map后在View中重绘片段-Android

[英]Redraw Fragment in View after initialising Google Map - Android

我想在个人资料视图的半屏上显示Google Map。 在我的onCreate方法中,我创建了AsyncTask的新实例,以通过JSON从Google服务器检索纬度和经度。 收到结果后,我致电:

GoogMapHandler gmh = new GoogMapHandler(fragmentManager, applicationContext);
gmh.initilizeMap(coord, "Username", "addressInfo");

这是我的GoogMapHandler类:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.widget.Toast;
import android.support.v4.app.FragmentManager;
import android.util.Log;

import com.google.android.gms.internal.fm;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class GoogMapHandler {
    // Google Map
    private GoogleMap googleMap;
    private android.support.v4.app.FragmentManager fragmentManager;
    private Context applicationContext;

    public GoogMapHandler(FragmentManager fmanager, Context applicationContext) {
        this.fragmentManager = fmanager;
        this.applicationContext = applicationContext;
    }

    public void initilizeMap(LatLng coord, String username, String addrInfo) {
        if (googleMap == null) {
            Fragment fragment = this.fragmentManager.findFragmentById(R.id.map);
            FragmentTransaction fragTransaction = this.fragmentManager
                    .beginTransaction();
            fragTransaction.detach(fragment);
            SupportMapFragment supportmapfragment = (SupportMapFragment) fragment;
            googleMap = supportmapfragment.getMap();

            if (googleMap == null) {
                Toast.makeText(applicationContext,
                        "Sorry! Unable to create map.", Toast.LENGTH_SHORT)
                        .show();
            } else {
                Marker loc = googleMap.addMarker(new MarkerOptions()
                        .position(coord).title("User: " + username)
                        .snippet(addrInfo));
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord,
                        15));
                fragTransaction.attach(fragment);
                fragTransaction.commit();
            }
        }
    }
}

现在的问题是,尽管没有错误,但我看不到地图。 由于已经创建了View,因此我试图“重绘”片段以显示地图,但是它不起作用。

我该如何实现?

任何帮助将不胜感激。

编辑:

这是我的ProfileActivity 如建议的那样,我使用onResume创建AsyncTask

public class ProfileActivity extends BaseActivity {
    private String username, address, postalCode, country;

    @Override
    protected void onResume() {
        Log.i("URL",
                "http://maps.googleapis.com/maps/api/geocode/json?address="
                        + address.replaceAll("\\s+", "+") + ",+" + postalCode
                        + ",+" + country + "&sensor=false");

        new LocationTask(getSupportFragmentManager(),
                getApplicationContext())
                .execute("http://maps.googleapis.com/maps/api/geocode/json?address="
                        + address.replaceAll("\\s+", "+")
                        + ",+"
                        + postalCode
                        + ",+" + country + "&sensor=false");
        super.onResume();

    }

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

        Intent intent = getIntent();
        username = intent.getStringExtra(SearchResultsActivity.USERNAME);
        if (username != null) {
            setTitle("User: " + username);
        }


        address = intent.getStringExtra(SearchResultsActivity.ADDRESS);
        postalCode = intent
                .getStringExtra(SearchResultsActivity.POSTALCODE);
        country = intent.getStringExtra(SearchResultsActivity.COUNTRY);

        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(username);

        setContentView(textView);

    }
}

配置文件布局:

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

    <FrameLayout
        android:id="@+id/map_frame"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.2" >

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />
    </FrameLayout>

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="TextView" />

</LinearLayout>

定位任务:

public class LocationTask extends
        AsyncTask<String, String, StringBuilder> {

    private EditText address = null;
    private EditText postalCode = null;
    private EditText country = null;

    private Context applicationContext;
    private FragmentManager fragmentManager;
    private LatLng coord;

    public LocationTask(FragmentManager fmanager,
            Context applicationContext) {
        this.fragmentManager = fmanager;
        this.applicationContext = applicationContext;
    }



    @Override
    protected StringBuilder doInBackground(String... params) {
        HttpGet httpGet = new HttpGet(params[0]);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(httpGet);
            StringBuilder stringBuilder = new StringBuilder();
            try {
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stringBuilder;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(StringBuilder result) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(result.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String postal_code = null;
        String street_address = null;
        String country = null;
        try {
            String status = jsonObject.getString("status").toString();
            if (status.equalsIgnoreCase("OK")) {
                JSONArray results = jsonObject.getJSONArray("results");                 
                    JSONObject r = results.getJSONObject(0);
                    JSONArray addressComponentsArray = r
                            .getJSONArray("address_components");
                    JSONObject geometry = r.getJSONObject("geometry");
                    JSONObject locationObj = geometry.getJSONObject("location");

                    coord = new LatLng(locationObj.getDouble("lat"), locationObj.getDouble("lng"));

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

            GoogMapHandler gmh = new GoogMapHandler(fragmentManager, applicationContext);
            gmh.initilizeMap(coord, "Username", "addressInfo");

    }
}

我忘记在ProfileActivity删除它:

        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(username);

        setContentView(textView);

删除它,解决了我的问题。

我不能发表评论

您确定代码在IF块中吗?

 public void initilizeMap(LatLng coord, String username, String addrInfo) {
    if (googleMap == null) {
       //are you getting upto here?
    ....
    }
 }

如果在布局中声明了SupportMapFragment,我认为detach在这里不会做任何有意义的事情。 以下应该工作:

public void initilizeMap(LatLng coord, String username, String addrInfo) {
    if (googleMap == null) {
        Fragment fragment = this.fragmentManager.findFragmentById(R.id.map);            
        SupportMapFragment supportmapfragment = (SupportMapFragment) fragment;
        googleMap = supportmapfragment.getMap();

        if (googleMap == null) {
            Toast.makeText(applicationContext,
                    "Sorry! Unable to create map.", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Marker loc = googleMap.addMarker(new MarkerOptions()
                    .position(coord).title("User: " + username)
                    .snippet(addrInfo));
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord, 15));
        }
    } else {
            Marker loc = googleMap.addMarker(new MarkerOptions()
                    .position(coord).title("User: " + username)
                    .snippet(addrInfo));
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord, 15));
}

如果上述方法不起作用,则问题不太可能出在代码块中,而是可能在映射准备就绪之前被调用。 请给我们更多信息; 告诉我们在调用onResume()之前AsyncTask是否可能返回结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM