25

I'm having some trouble when i want to get current location.

This is my first time using this GM API, and there are so much things i don't understand.

Here is my code, and i want

var geocoder = new google.maps.Geocoder();

function initialize() {
  var latLng = new google.maps.LatLng(-7.7801502, 110.3846387);
  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 15,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var marker = new google.maps.Marker({
    position: latLng,
    title: 'Ambarrukmo Plaza Yogyakarta',
    map: map,
    draggable: true
  });
}

The problem is, i want to change -7.7801502 and 110.3846387 value automatically based on user's current position. Can i do that?

Thanks before for your help and explanation.

Another question : -> What if i'm going to change those value based on a device embedded with GPS?

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
Arvid Theodorus
  • 443
  • 2
  • 9
  • 20

5 Answers5

39

You can't get current user's location with Google Maps. However, if you get Google Maps with Google Loader, you can use the google.loader.CurrentLocation to get a location based on IP.

An other way is to use the HTML5 GeoLocation API.

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    alert("Geolocation is not supported by this browser.");
  }
}
function showPosition(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  map.setCenter(new google.maps.LatLng(lat, lng));
}
Community
  • 1
  • 1
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
9

For people looking for a solution in the future, Google now has a Geolocation example on the Google Maps page > https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

NetOperator Wibby
  • 1,354
  • 5
  • 22
  • 44
1

If you want to stay in the world of google maps API, and assuming you have the map variable you can use,

var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);

var myLat = map.center.k;
var myLng = map.center.B;

or you could use,

alert("Lat="+map.center.k);
alert("Lng="+map.center.B);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
import UIKit
import GoogleMaps
import GooglePlaces
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate,GMSMapViewDelegate {

@IBOutlet weak var currentlocationlbl: UILabel!


var mapView:GMSMapView!

var locationManager:CLLocationManager! = CLLocationManager.init()

var geoCoder:GMSGeocoder!

var marker:GMSMarker!

var initialcameraposition:GMSCameraPosition!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.mapView = GMSMapView()
    self.geoCoder = GMSGeocoder()
    self.marker = GMSMarker()
    self.initialcameraposition = GMSCameraPosition()

    // Create gms map view------------->
    mapView.frame = CGRect(x: 0, y: 150, width: 414, height: 667)
    mapView.delegate = self
    mapView.isMyLocationEnabled = true
    mapView.isBuildingsEnabled = false
    mapView.isTrafficEnabled = false
    self.view.addSubview(mapView)

    // create cureent location label---------->

    self.currentlocationlbl.lineBreakMode = NSLineBreakMode.byWordWrapping
    self.currentlocationlbl.numberOfLines = 3
    self.currentlocationlbl.text = "Fetching address.........!!!!!"

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))
    {
        self.locationManager.requestAlwaysAuthorization()
    }
    self.locationManager.startUpdatingLocation()

    if #available(iOS 9, *)
    {
    self.locationManager.allowsBackgroundLocationUpdates = true
    }
    else
    {
        //fallback earlier version
    }
    self.locationManager.startUpdatingLocation()


    self.marker.title = "Current Location"
    self.marker.map = self.mapView


    // Gps button add mapview

    let gpbtn:UIButton! = UIButton.init()
    gpbtn.frame = CGRect(x: 374, y: 500, width: 40, height: 40)
    gpbtn.addTarget(self, action: #selector(gpsAction), for: .touchUpInside)
    gpbtn.setImage(UIImage(named:"gps.jpg"), for: .normal)
    self.mapView.addSubview(gpbtn)
    }

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    var location123 = CLLocation()

    location123 = locations[0]

    let coordinate:CLLocationCoordinate2D! = CLLocationCoordinate2DMake(location123.coordinate.latitude, location123.coordinate.longitude)

    let camera = GMSCameraPosition.camera(withTarget: coordinate, zoom: 16.0)

    self.mapView.camera = camera
    self.initialcameraposition = camera
    self.marker.position = coordinate
    self.locationManager.stopUpdatingLocation()

}


func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition)
{
    self.currentAddres(position.target)
}

func currentAddres(_ coordinate:CLLocationCoordinate2D) -> Void
{
    geoCoder.reverseGeocodeCoordinate(coordinate) { (response, error) in

        if error == nil
        {
            if response != nil
            {

                let address:GMSAddress! = response!.firstResult()

                if address != nil
                {
                   let addressArray:NSArray! = address.lines! as NSArray

                    if addressArray.count > 1
                    {
                        var convertAddress:AnyObject! = addressArray.object(at: 0) as AnyObject!
                        let space = ","
                        let convertAddress1:AnyObject! = addressArray.object(at: 1) as AnyObject!
                        let country:AnyObject! = address.country as AnyObject!

                        convertAddress = (((convertAddress.appending(space) + (convertAddress1 as! String)) + space) + (country as! String)) as AnyObject

                        self.currentlocationlbl.text = "\(convertAddress!)".appending(".")
                    }
                    else
                    {
                        self.currentlocationlbl.text = "Fetching current location failure!!!!"
                    }

                }


            }
        }
    }
}

...

Isma
  • 14,604
  • 5
  • 37
  • 51
nandhu
  • 9
  • 4
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Isma Dec 11 '17 at 12:49
0

For those interested, another suggested approach which retrieves the user's current location and then shows Google Maps.

https://codepen.io/easyisez/pen/mdGgMdG

JS code:

(function (global) {
"use strict";

// Callback function passed: showMap
function getLocation(callback) {
    navigator.geolocation.getCurrentPosition(function (pos) {
        callback({
            "latitude": pos.coords.latitude,
            "longitude": pos.coords.longitude,
            "status": 0,
            "description": ""});
    }, function (err) {
        // Failure reported by the browser's getCurrentPosition method
        callback({
            "latitude": null,
            "longitude": null,
            "status": -1,
            "description": `ERROR (${err.code}): ${err.message}`});
    });
}


$(document).ready(function () {
    var showMap = function (appState) {
        if (appState.status === 0) {
            var map = new google.maps.Map(document.getElementById('map'), {
                    center: {lat: appState.latitude, lng: appState.longitude},
                    zoom: 20,
                    mapTypeId: 'satellite',
                    streetViewControl: false
            });
            
        } else {
            // Handle error
        }
    }

    // Disable AJAX caching
    $.ajaxSetup({cache: false});

    // Get the weather for the current location
    getLocation(showMap);

});

}(this));

For more details, visit the my CodePen project. Enjoy.

Erwin Zoer
  • 21
  • 5