简体   繁体   English

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

[英]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.

相关问题 当网络服务中的经度和纬度发生变化时,如何在Google地图中移动标记? - How to move the marker in Google map when the latitude and longitude changes in webservices? 如何从我在地图上设置的标记保存经度和纬度 - How to save longitude and latitude from the marker i set on the map 如何在Google Map v2中获取标记的经度和纬度值 - How to get the longitude and latitude value of the marker in google map v2 我想通过从json获取经度和纬度在Google地图上显示标记 - i want to show marker on google map by getting longitude and latitude from json 如何从谷歌地图 URL 获取纬度经度 - How to get latitude longitude from google map URL 如何使用MSExcel中的纬度和经度对在Google地图上移动标记并每10秒刷新一次 - How can I move a marker on Google Maps using latitude & longitude pair from MSExcel and refresh every 10 seconds 如何从地图中的标记获取纬度和经度 - How to get latitude and longitude from a mark in the map 转换谷歌地图中的纬度和经度? - converting latitude and longitude in google map? 我想从 Cloud Firestore 数据库中获取纬度和经度以在 map Android Studio 上添加标记 - I want to get latitude and longitude from Cloud Firestore database to add markers on map Android Studio 如何从Android中的Google Map获取2点之间的点(经度和纬度)? - How to get the points( Latitude and Longitude) between 2 points from google map in android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM