logo
down
shadow

How to get latitude and longitude in Android phone?


How to get latitude and longitude in Android phone?

By : Walter Oresto
Date : November 29 2020, 01:01 AM
Any of those help Google Longitude was something else. The location API uses LocationManager and has never been deprecated.
code :


Share : facebook icon twitter icon
How can I get longitude, latitude of phone in Android?

How can I get longitude, latitude of phone in Android?


By : user1765343
Date : March 29 2020, 07:55 AM
will be helpful for those in need LocationManager can return a last known location but this is not very precise so you have to request location updates and wait for the first one. Then you can continue receiving them or cancel them. You can request both network and GPS updates.
If you are using a phone to test your code then you have to wait for a GPS fix, and this can take a while. Network provider should be much faster.
Sending Longitude, Latitude & Phone Number to mysql database - Android

Sending Longitude, Latitude & Phone Number to mysql database - Android


By : user5020953
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You need to create MySql Database on a server and call Web service to add that data on the server using Php.
Look at this tutorial . Here you can find how to send and receive data using php web service.
Find Latitude and Longitude with out using internet in my android phone

Find Latitude and Longitude with out using internet in my android phone


By : Kenneth Cambaya
Date : March 29 2020, 07:55 AM
Does that help I want to get latitude and longitude in my android application. Please provide me a code for my android application to get latitude and longitude with out using internet..thanks , You can try this, it works for me:
code :
public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}
gps = new GPSTracker(PromotionActivity.this);

// check if GPS enabled     
if(gps.canGetLocation()){
    double latitude = gps.getLatitude();
    double longitude = gps.getLongitude();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
    gps.showSettingsAlert();    
}
How to send my location (longitude and latitude) as an SMS to another cell phone in android

How to send my location (longitude and latitude) as an SMS to another cell phone in android


By : Seth W.
Date : March 29 2020, 07:55 AM
it fixes the issue I want to know how to send my coordinates via SMS by clicking a button. I have the following code that a message is sent, as sending the coordinates. , Follow these steps
code :
     String msg_txt =""; 
     // Declare as global variable

     Enviar.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                 PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

                try {
                     startActivityForResult(builder.build(ComposeThreadsActivity.this), PLACE_PICKER_REQUEST);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        if (data != null) {
            if (requestCode == PLACE_PICKER_REQUEST) {
                if (resultCode == RESULT_OK) {
                    Place place = PlacePicker.getPlace(data, this);
                    String toastMsg = String.format("Place: %s",
                            place.getName());
                    String address = String.valueOf(place.getAddress());
                    String placeName = String.valueOf(place.getName());

                    LatLng latLong = place.getLatLng();
                    String lat = String.valueOf(latLong.latitude);
                    String lon = String.valueOf(latLong.longitude);
                    StringBuilder sb = new StringBuilder();
                    if (!TextUtils.isEmpty(placeName)) {
                        if (placeName.contains(lat)) {

                            sb.append("http://maps.google.com/?q=" + lat + ","
                                    + lon);
                        } else {
                            sb.append("Place: " + placeName);
                            if (!TextUtils.isEmpty(address)) {
                                sb.append("\nAddress: " + address);
                            }
                            sb.append("\nLink: http://maps.google.com/?q="
                                    + lat + "," + lon);
                        }
                        msg_txt = sb.toString();
                        EnviarMensaje("cell phone number", msg_txt);

                    }

                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
How to manage to take latitude and longitude of my android phone in cordova?

How to manage to take latitude and longitude of my android phone in cordova?


By : user1824612
Date : March 29 2020, 07:55 AM
I wish did fix the issue. When you press your button it submits your form "form_1" and probably page is reloaded. That can be a reason. Try to move the button out of the form, or add another without type="submit".
In the first time when you try to check geolocation you can be askd about permissions. Check if you didn't deny it my mistake.
code :
cordova plugin add cordova-plugin-geolocation
<div class="app">
        <h1>Apache Cordova</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
            <button id="geo-button" class="button">Geo</div>
        </div>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
var app = {
// Application Constructor
initialize: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},

// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
    this.receivedEvent('deviceready');
},

// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);

    const geoButton = document.getElementById('geo-button');

    geoButton.addEventListener('click', function(e) {
        navigator.geolocation.getCurrentPosition(function(position) {
            alert('Latitude: '          + position.coords.latitude          + '\n' +
              'Longitude: '         + position.coords.longitude         + '\n' +
              'Altitude: '          + position.coords.altitude          + '\n' +
              'Accuracy: '          + position.coords.accuracy          + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
              'Heading: '           + position.coords.heading           + '\n' +
              'Speed: '             + position.coords.speed             + '\n' +
              'Timestamp: '         + position.timestamp                + '\n');
        }, function onError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        });
    });
}}
<edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
    <string>need location access to find things nearby</string>
</edit-config>
Related Posts Related Posts :
  • Why is it mandatory for ternary operations to return a value?
  • How can I make my listview rows different heights
  • Array declaration trick : Is it bad to use it?
  • Calling different classes with if else statements
  • Free API for speech recognition system
  • Java: Objects in JFrame are messed up
  • Is there a similar of MessageBox of ExtJS in ADF Faces
  • Passing HttpServletResponse in Spring Boot controller method
  • Failed to load libraries: [netty_tcnative_linux_arm_32, netty_tcnative_linux_arm_32_fedora, netty_tcnative_arm_32, netty
  • How to build a small documents storage?
  • Getting pixel position of a text in an image
  • How do I get a list of Methods called from a Class in Eclipse IDE?
  • Convert string to day of week (not exact date)
  • Unable to understand how rounding is working for decimal digits (Java)
  • How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)
  • JTable Renderer not working with RowSorter?
  • From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?
  • jUnit tests work in Eclipse, but fail in ant - java.lang.RuntimeException: Stub
  • How do i add a tooltip to existing gwt Textbox?
  • actor replying to non-actor
  • Google Cloud Messaging - server connection
  • Which classes are unmodifiable and cannot be intrumented and is there a way to bypass it?
  • Java & Jersey 1.17: Custom default response headers
  • Java rounding error
  • Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?
  • Arquillian test class variables lose value
  • java.util.ConcurrentModificationException while inserting in ArrayList
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • Elegant way to create one of a large number of classes
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org