[英]How to add marker in google map when i recieve longitude and latitude from sms
So basically I am making an app in which I would get an SMS which will contain a latitude and longitude from which I need to add a new marker on the map. 因此,基本上,我正在开发一个应用程序,在该应用程序中,我将收到一条包含经度和纬度的SMS,需要在其中添加地图上的新标记。 But I am unable to do so as I cannot add marker outside the onMapReady function.
但是我无法这样做,因为无法在onMapReady函数之外添加标记。 Any suggestion on how to add marker outside the onMapReady function?
关于如何在onMapReady函数之外添加标记的任何建议? the maps activity is as follow package com.example.rajen.railwaycrackk;
地图活动如下:com.example.rajen.railwaycrackk包;
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;
}
}
My SMS broadcast receiver is as follows 我的SMS广播接收器如下
package com.example.rajen.railwaycrackk;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
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.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* Created by rajen on 29-01-2018.
*/
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public static final String ADD_MARKER = "some.unique.string.ADD_MARKER";
private GoogleMap mMap;
public SmsReceiver (GoogleMap mMap) {
this.mMap = mMap;
}
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
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
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
// LatLng position = new LatLng(20.5937, 78.9629);
// MapsActivity.plotOnMap(position);
} // end for loop
} // bundle is null
Intent broadcastIntent = new Intent();
// get 'lat' and 'lng' from message
broadcastIntent.setAction(SmsReceiver.ADD_MARKER);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("lat", 10);
broadcastIntent.putExtra("lng", 10);
LocalBroadcastManager.getInstance(context.getApplicationContext()).sendBroadcast(broadcastIntent);
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}
Use a broadcast receiver attached to your map activity.... 使用连接到地图活动的广播接收器。
Create a BroadcastReceiver subclass as follows: 创建一个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
}
}
}
In your map activity 'onMapReady' register the local broadcast receiver: 在地图活动“ 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);
}
... and where you receive the SMS: ...以及您收到短信的位置:
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);
You may find you'll want to do more things than ADD_MARKER so just update MapRequestReceiver with more actions (strings) and update 'onReceive'. 您可能会发现自己想做的事情比ADD_MARKER还要多,因此只需使用更多操作(字符串)更新MapRequestReceiver并更新“ onReceive”即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.