MapKit, Set current location manually ? It is possible? - swift

How to display current location from coordinates manually? I am taking coordinates from another GPS device. How to set it manually?

Where the coordinates come from is largely immaterial: as long as you have one you can set the map to display an area including that point. If you want to display the point itself you can add an annotation:
A simple example method to drop a pin and zoom in to its location:
func createAnnotation(from coordinate: CLLocationCoordinate2D, title: String) -> MKPointAnnotation {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = title
return annotation
}
func dropPinAndZoomIn(to coordinate: CLLocationCoordinate2D){
var spanDelta = 0.035 //the width/height of the map area in degrees
let annotation = createAnnotation(from: coordinate, title: "My Location")
mapView.removeAnnotations(mapView.annotations) //clear any prev annotations
mapView.addAnnotation(annotation)
let span = MKCoordinateSpan(latitudeDelta: spanDelta, longitudeDelta: spanDelta)
let region = MKCoordinateRegion(center: coordinate, span: span)
let displayRegion = mapView.regionThatFits(region) //ensure the region can be displayed in the mapView's view
mapView.setRegion(displayRegion, animated: true)
}

Related

MKMapItem Center for creating annotations

I am trying to perform an MKLocalSearch.Request() and display the result on my mapView similar to this tutorial however when I do the search the coordinates returned are off center from where they should be. Where the map displays Brooklyn as an overlay in the center of the borough correctly the annotation is far off center to the left. I've noticed that there are two sets of coordinates contained in MKMapItem one the location and the other shown as center when printed to the console. I am not sure how to access the center coordinate but the center coordinate is the correct one in the middle of the screen. How can I access the center coordinate to use as the MKAnnotation's coordinate? Thank you
Search Code
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = "brooklyn"
searchRequest.region = MKCoordinateRegion(center: CLLocationCoordinate2DMake(40.758896, -73.985130), latitudinalMeters: 2000, longitudinalMeters: 2000)
let search = MKLocalSearch(request: searchRequest)
search.start { (response, error) in
if let error = error{
print("Error performing search for location")
}
if let response = response{
for item in response.mapItems{
print("map item returned: \(item)")
print("latitude: \(item.placemark.coordinate.latitude) longitude: \(item.placemark.coordinate.longitude)")
let annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
self.mapView.addAnnotation(annotation)
}
}
}
Output
map item returned: Optional(CLCircularRegion (identifier:'<+40.64529796,-73.94483550> radius 14090.15', center:<+40.64529796,-73.94483550>, radius:14090.15m))
latitude: 40.6924599 longitude: -73.9903805
I was able to access the center by casting the region property of MKMapItem's placemark property from CLRegion to CLCircularRegion.
if let response = response{
for item in response.mapItems{
print("map item returned: \(item.placemark)")
if let region = item.placemark.region as? CLCircularRegion{
print("region.center: \(region.center)")
let annotation = MKPointAnnotation()
annotation.coordinate = region.center
annotation.title = item.name
self.mapView.addAnnotation(annotation)
}
}

how to keep the current location dot on the centre of the map when moving, google map, swift

In my project I am using google map. I am enabling the current location dot like this:
self.mapView?.isMyLocationEnabled = true
After that I am getting the current location latitude and longitude like this:
guard let currentLat = self.mapView?.myLocation?.coordinate.latitude,
let currentLan = self.mapView?.myLocation?.coordinate.longitude else {
showMessageFail(title: "Fail", myMessage: "Could not determine your current location")
return
}
And then focusing the camera on current location like this:
let currentPosition = CLLocationCoordinate2D(latitude: currentLat, longitude: currentLan)
self.mapView?.animate(toLocation: self.currentPosition)
Everything is perfectly fine, now it shows the current location dot (the blue dot on google map) on the centre of the map. Now when current location changed, say I am in a car the current location dot moves, at some point it moves out of the bounds of the map. How can I always keep the current location dot on the centre of the map and move the map not the dot. Any help would be really appreciated.
currLocation = manager.location!
let locationOfDevice: CLLocation = currLocation // this determines the location of the device using the users location
let deviceCoordinate: CLLocationCoordinate2D = locationOfDevice.coordinate // determines the coordinates of the device using the location device variabel which has in it the user location.
let span = MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1) // this determines the span in which its determined that 1 degree is 69 miles.
let region = MKCoordinateRegion(center: deviceCoordinate, span: span) // set the center equal to the device coordinates and the span equal to the span variable we have created this will give you the region.
mapView.setRegion(region, animated: true);
CLLocation *newMyLocation = [[CLLocation alloc] initWithLatitude:_locationManager.location.coordinate.latitude longitude:_locationManager.location.coordinate.longitude];
_cmarker.position = newMyLocation.coordinate;
CGPoint point1 =[_mapkitView.projection pointForCoordinate:newMyLocation.coordinate];
point1.y = -400;
GMSCameraUpdate *cameraUpdate = [GMSCameraUpdate setTarget:[_mapkitView.projection coordinateForPoint:point1]];
[_mapkitView animateWithCameraUpdate:cameraUpdate];
_cmarker.map = self.mapkitView;
//[_mapkitView setCenterCoordinate:newMyLocation.coordinate zoomLevel:_mapkitView.zoomLevel animated:YES];
[_mapkitView animateToLocation:CLLocationCoordinate2DMake(newMyLocation.coordinate.latitude, newMyLocation.coordinate.longitude)];
[_mapkitView animateToZoom:_mapkitView.camera.zoom]; // animate to that zoom level

How to draw a route between two markers in google maps (swift )?

I want to show direction between two markers that I had made. How can I do it? How can I show direction?
Here is my code that I used to make markers:
func mapView(mapView: GMSMapView, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {
if counterMarker < 2
{
counterMarker += 1
let marker = GMSMarker(position: coordinate)
marker.appearAnimation = kGMSMarkerAnimationPop
marker.map = mapView
marker.position.latitude = coordinate.latitude
marker.position.longitude = coordinate.longitude
print(marker.position.latitude)
print(marker.position.longitude)
}
And here is the code for deleting markers on click:
func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
let alert = UIAlertController(title: "Alert", message: "Are you Sure for deleting ?!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("No Pressed")
})
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("Yes Pressed")
marker.map = nil
self.counterMarker -= 1
})
self.presentViewController(alert, animated: true, completion: nil)
return true
}
And I like to show which marker is for destination and which one is for origin.
Use Polylines which allows you to draw lines on the map. You'll need to specify its path by creating a corresponding GMSMutablePath object with two or more points. Each CLLocationCoordinate2D represents a point on the Earth's surface. Line segments are drawn between points according to the order in which you add them to the path.
Example:
let path = GMSMutablePath()
path.addCoordinate(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
path.addCoordinate(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
path.addCoordinate(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
path.addCoordinate(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
path.addCoordinate(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
let rectangle = GMSPolyline(path: path)
rectangle.map = mapView
Check these related links:
Drawing Route Between Two Places on GMSMapView in iOS
Google Maps for iOS, swift - How to show entire polyline between markers?
For Swift 2.0 Google Maps, to make your map view fit the polyline of
the route you are drawing:
let path: GMSPath = GMSPath(fromEncodedPath: route)!
routePolyline = GMSPolyline(path: path)
routePolyline.map = mapView
var bounds = GMSCoordinateBounds()
for index in 1...path.count() {
bounds = bounds.includingCoordinate(path.coordinateAtIndex(index))
}
mapView.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds))
Hope this helps! :)
Use GMSPolyline and set its map property to your GMSMapView to draw polyline/route on your map

MapKit default zoom

For some reason my market won't zoom to the local region. In fact, it does not change the zoom no matter what I change. Am I loading it in the wrong part of the code, or am I missing something else? Any help is appreciated.
My code is:
#IBOutlet var here: MKMapView!
var locationManager: CLLocationManager?
var selectedItem: String?
func locationManager
(manager: CLLocationManager!,didUpdateToLocation newLocation: CLLocation!,
fromLocation oldLocation: CLLocation!){
manager.desiredAccuracy = kCLLocationAccuracyBest
var region = self.here.region as MKCoordinateRegion
self.here.setRegion(region, animated: true)
region.span.longitudeDelta = 0.0144927536
region.span.latitudeDelta = 0.0144927536
}
I believe you need to set the lat and long BEFORE you set the region. The setRegion function is what zooms in on a certain part, and the level of the zoom depends on your span. Here's an example of a map that zooms.
let span = MKCoordinateSpanMake(0.075, 0.075)
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: lat, longitude: long), span: span)
mapView.setRegion(region, animated: true)

Change Initial Zoom MapKit Swift

I'm new in Swift, and I'm trying to use MkMapView. I'd like to change the initial zoom. I searched On the API but I don't find anything.
I find only this, about zoom
mapView.zoomEnabled = true
But it isn't what I looking For.
MKMaps don't have a concept of zoom as a configurable variable. Zoom enabled pertains to user interaction. You'll need to configure something manually by setting a region that encompasses your desired zoom level.
For instance, if I wanted to zoom in on some specific coordinate, I could do:
let coordinate: CLLocationCoordinate2D = // .. populate your center
let latitudinalMeters: CLLocationDistance = 50
let longitudinalMeters: CLLocationDistance = 50
let region = MKCoordinateRegionMakeWithDistance(coordinate, latitudinalMeters, longitudinalMeters)
self.mapView.setRegion(region, animated: false) // Set to yes to animate, you said initial load so I image this won't be visible anyways.
Then, adjust the latitudinal/longitudinal dimensions to meet your desired zoom level.
If you wanted, you could probably create a category that adds zoom and calls this in the background.
From Logan's answer, update for Swift 5+
let coordinate: CLLocationCoordinate2D = // .. populate your center
let latitudinalMeters: CLLocationDistance = 50
let longitudinalMeters: CLLocationDistance = 50
let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: latitudinalMeters, longitudinalMeters: longitudinalMeters)
self.mapView.setRegion(region, animated: false) // Set to yes to animate, you said initial load so I image this won't be visible anyways.