当我从短信接收经度和纬度时,如何在谷歌地图中添加标记

时间:2018-02-18 19:18:19

标签: java android google-maps-android-api-2

所以基本上我正在制作一个应用程序,我会收到一条短信,其中包含我需要在地图上添加新标记的纬度和经度。但我无法这样做,因为我无法在onMapReady函数之外添加标记。关于如何在onMapReady函数外添加标记的任何建议? 地图活动如下 包com.example.rajen.railwaycrackk;

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
    return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
    let sendLocation = SendLocation()

    sendLocation.determineCurrentLocation()
}

我的短信广播接收器如下

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    boolean sms_Perm=true;
    private GoogleMap mMap;
    boolean mapstart=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this, Manifest.permission.RECEIVE_SMS)) {
                ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
            } else {
                ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
            }

        }
        // 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);
        if (mMap!=null) {
//          GoogleMap  map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
//                    .getMap();
            Log.d("1", "entered into truee");

            this.mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(10, 10))
                    .title("Hello world"));

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestcode, String[] permissions, int[] grantResults) {
        switch (requestcode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
                        sms_Perm = true;

                    }

                } else {
                    Toast.makeText(this, "No permission granted", Toast.LENGTH_SHORT).show();
                    sms_Perm = false;
                }

            }

        }
    }
    public void onMapReady(GoogleMap googleMap) {
        this.mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(20.5937, 78.9629);
        this.mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        this.mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mapstart=true;

        SmsReceiver myMapReceiver = new SmsReceiver(googleMap);
        IntentFilter filter = new IntentFilter(SmsReceiver.ADD_MARKER);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(myMapReceiver, filter);
    }


    public String LoadInt(String key){
        String savedValue;
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        savedValue = sharedPreferences.getString(key,null);
        return savedValue;
    }
}

1 个答案:

答案 0 :(得分:0)

使用附加到地图活动的广播接收器......

创建BroadcastReceiver子类,如下所示:

  public class MapRequestReceiver extends BroadcastReceiver {

     public static final String ADD_MARKER = "some.unique.string.ADD_MARKER";

     private GoogleMap mMap;

     public MapRequestReceiver (GoogleMap mMap) {
        this.mMap = mMap;
     }

     public void onReceive(Context context, Intent intent) {
        if (intent.getAction().compareTo(ADD_MARKER) == 0) {
           double lat = intent.getDoubleExtra("lat", 0);
           double lng = intent.getDoubleExtra("lng", 0);

           // do something with map using lat/lng
        }
     }

  }

在你的地图活动' onMapReady'注册本地广播接收器:

  public void onMapReady(GoogleMap googleMap) {

     // ... other stuff...

     // check if it already exists in which case do nothing or 
     // unregister it first using LocalBroadcastManager.

     MapRequestReceiver myMapReceiver = new MapRequestsReceiver(googleMap);
     IntentFilter filter = new IntentFilter(MapRequestReceiver.ADD_MARKER);
     filter.addCategory(Intent.CATEGORY_DEFAULT);
     LocalBroadcastManager.getInstance(this).registerReceiver(myMapReceiver, filter);
  }

...以及收到短信的地方:

  Intent broadcastIntent = new Intent();
  // get 'lat' and 'lng' from message
  broadcastIntent.setAction(MapRequestsReceiver.ADD_MARKER);
  broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
  broadcastIntent.putExtra("lat", lat);
  broadcastIntent.putExtra("lng", lng);
  LocalBroadcastManager.getInstance( getApplicationContext() ).sendBroadcast(broadcastIntent);

你可能会发现你想做的事情比ADD_MARKER更多,所以只需用更多动作(字符串)更新MapRequestReceiver并更新' onReceive'。