I want these lines to be visible on a regular map in such a way where each square represents 1x1m.
I looked into MKTileOverlay but didn't find too much about it. Is it possible to show the gridline on the map as well as change the color?
I've done something very similar for an app I've been playing around with. Mine is for putting a coloured grid over a map so that there are 15 columns and rows in a square mile around a home location, so you'll need to adjust the calculations for your distances but the same general approach should work. The app is only a prototype at the moment, and hasnt been optimised (could refactor code out of viewDidLoad for a start!), but the code should be good enough to get you started.
var homeLocation: CLLocationCoordinate2D!
let metresPerMile = 1609.344
var degPerHorizEdge: Double!
var degPerVertEdge: Double!
override func viewDidLoad() {
homeLocation = CLLocationCoordinate2D(latitude: 53.7011, longitude: -2.1071)
let hd = CLLocation(latitude: homeLocation.latitude, longitude: homeLocation.longitude).distance(from: CLLocation(latitude: homeLocation.latitude + 1, longitude: homeLocation.longitude))
let vd = CLLocation(latitude: homeLocation.latitude, longitude: homeLocation.longitude).distance(from: CLLocation(latitude: homeLocation.latitude, longitude: homeLocation.longitude + 1))
let degPerHMile = 1 / (hd / metresPerMile)
let degPerVMile = 1 / (vd / metresPerMile)
degPerHorizEdge = degPerHMile / 15
degPerVertEdge = degPerVMile / 15
super.viewDidLoad()
let gridController = GridController(for: gameID!)
gridController.delegate = self
let mapSize = CLLocationDistance(1.2 * metresPerMile)
let region = MKCoordinateRegion(center: homeLocation, latitudinalMeters: mapSize, longitudinalMeters: mapSize)
mapView.delegate = self
mapView.showsUserLocation = true
mapView.showsBuildings = true
mapView.mapType = .standard
mapView.setRegion(region, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let overlays = prepareOverlays() {
mapView.addOverlays(overlays)
}
}
func prepareOverlays() -> [MKPolygon]? {
let topLeft = CLLocationCoordinate2D(latitude: homeLocation.latitude - 7.5 * degPerHorizEdge, longitude: homeLocation.longitude - degPerVertEdge * 7.5)
var overlays = [MKPolygon]()
var locations = [CLLocationCoordinate2D]()
for y in 0...14 {
for x in 0...14 {
locations.append(CLLocationCoordinate2D(latitude: topLeft.latitude + Double(x) * degPerHorizEdge, longitude: topLeft.longitude + Double(y) * degPerVertEdge))
}
}
for coord in locations.enumerated() {
let location = coord.element
var corners = [location, //has to be a var due to using pointer in next line
CLLocationCoordinate2D(latitude: location.latitude + degPerHorizEdge, longitude: location.longitude),
CLLocationCoordinate2D(latitude: location.latitude + degPerHorizEdge, longitude: location.longitude + degPerVertEdge),
CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude + degPerVertEdge)]
let overlay = MKPolygon(coordinates: &corners, count: 4)
overlay.title = "\(coord.offset)"
overlays.append(overlay)
}
return overlays.count > 0 ? overlays : ni
}
//MARK:- MKMapViewDelegate
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
// overlay is a WSW zone
if let polygon = overlay as? MKPolygon {
let renderer = MKPolygonRenderer(polygon: polygon)
renderer.strokeColor = UIColor.gray.withAlphaComponent(0.4)
renderer.fillColor = UIColor.orange.withAlphaComponent(0.5)
renderer.lineWidth = 2
return renderer
}
// overlay is a line segment from the run (only remaining overlay type)
else {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = UIColor.blue.withAlphaComponent(0.8)
renderer.lineWidth = 3
return renderer
}
}
}
Related
I'm using this class
import UIKit
import CoreLocation
import GoogleMaps
import GooglePlaces
import SwiftyJSON
import Alamofire
import MapKit
class FinalClass: UIViewController {
#IBOutlet weak var containerView: UIView!
#IBOutlet weak var bottomInfoView: UIView!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var distanceLabel: UILabel!
var userLocation:CLLocationCoordinate2D?
var places:[QPlace] = []
var index:Int = -1
var locationStart = CLLocation()
var locationEnd = CLLocation()
var mapView:GMSMapView!
var marker:GMSMarker?
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
guard index >= 0, places.count > 0 else {
return
}
let place = places[index]
let lat = place.location?.latitude ?? 1.310844
let lng = place.location?.longitude ?? 103.866048
// Google map view
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 12.5)
mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
self.containerView.addSubview(mapView)
// Add gesture
addSwipeGesture()
didSelect(place: place)
if userLocation != nil {
addMarkerAtCurrentLocation(userLocation!)
}
}
func addSwipeGesture() {
let directions: [UISwipeGestureRecognizerDirection] = [.right, .left]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
gesture.direction = direction
self.bottomInfoView.addGestureRecognizer(gesture)
}
}
func addMarkerAtCurrentLocation(_ userLocation: CLLocationCoordinate2D) {
let marker = GMSMarker()
marker.position = userLocation
marker.title = "Your location"
marker.map = mapView
}
func didSelect(place:QPlace) {
guard let coordinates = place.location else {
return
}
// clear current marker
marker?.map = nil
// add marker
marker = GMSMarker()
marker?.position = coordinates
marker?.title = place.name
marker?.map = mapView
mapView.selectedMarker = marker
moveToMarker(marker!)
// update bottom info panel view
let desc = place.getDescription()
descriptionLabel.text = desc.characters.count > 0 ? desc : "-"
distanceLabel.text = "-"
// update distance
if userLocation != nil {
let dist = distance(from: userLocation!, to: coordinates)
distanceLabel.text = String.init(format: "Distance %.2f meters", dist)
self.drawPath(startLocation: userLocation!, endLocation: coordinates)
}
title = place.name
}
func moveToMarker(_ marker: GMSMarker) {
let camera = GMSCameraPosition.camera(withLatitude: marker.position.latitude,
longitude: marker.position.longitude,
zoom: 12.5)
self.mapView.animate(to: camera)
}
// distance between two coordinates
func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
return from.distance(from: to)
}
func handleSwipe(sender: UISwipeGestureRecognizer) {
guard index >= 0, places.count > 0 else {
return
}
if sender.direction == .left {
if index < places.count - 2 {
index += 1
didSelect(place: places[index])
}
} else if sender.direction == .right {
if index > 1 {
index -= 1
didSelect(place: places[index])
}
}
}
func drawPath(startLocation: CLLocationCoordinate2D, endLocation: CLLocationCoordinate2D) {
let from = CLLocation(latitude: startLocation.latitude, longitude: startLocation.longitude)
let to = CLLocation(latitude: endLocation.latitude, longitude: endLocation.longitude)
let origin = "\(from.coordinate.latitude),\(from.coordinate.longitude)"
let destination = "\(to.coordinate.latitude),\(to.coordinate.longitude)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"
Alamofire.request(url).responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // HTTP URL response
print(response.data as Any) // server data
print(response.result as Any) // result of response serialization
let json = JSON(data: response.data!)
let routes = json["routes"].arrayValue
// print route using Polyline
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSPath.init(fromEncodedPath: points!)
let polyline = GMSPolyline.init(path: path)
polyline.strokeWidth = 4
polyline.strokeColor = UIColor.black
polyline.map = self.mapView
}
}
}
#IBAction func navigationStart(_ sender: Any) {
}
with a google maps to add place markers, draw the direction on the map and show the distance between two points, now i would like to launch the navigator between startLocation: userLocation! and endLocation: coordinates but with some research i saw that i can not launch the navigator in the same view, i need to open the maps application, so i decided to add the MapKit and a button
#IBAction func navigationStart(_ sender: Any) {
}
so how can i do that by pressing the button the map application opens with direction from userLocation to coordinates ? I already looked to similar question but is a little different to my problem, because i already have the points but in different format.
Your question is a little confusing but if you want to open the maps app and show direction from a user's current location to another point on the map then you don't need to pass the user's location, just the destination:
Swift 4:
let coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246)
let placeMark = MKPlacemark(coordinate: coordinate)
let mapItem = MKMapItem(placemark: placeMark)
mapItem.name = "Big Ben"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
Objective C:
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate: coordinate];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:#"Big Ben"];
[mapItem openInMapsWithLaunchOptions:#{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving}];
I have to plot multiple pins in a Google Map view, and then zoom to the user's current location. Pins are plotted successfully but not zoomed to current location. Any help would be appreciated
override func viewDidAppear(_ animated: Bool) {
if (self.googleMapsView == nil) {
self.googleMapsView = GMSMapView(frame: self.mapViewContainer.frame)
self.view.addSubview(self.googleMapsView)
print(AppDelegate.getAppDelegate().mapArray)
googleMapsView.clear()
for i in 0...AppDelegate.getAppDelegate().mapArray.count - 1 {
let lon = Double ((AppDelegate.getAppDelegate().mapArray[i]["lon"] as? String)!)
let lat = Double ((AppDelegate.getAppDelegate().mapArray[i]["lat"] as? String)!)
let tit = AppDelegate.getAppDelegate().mapArray[i]["location"] as? String
locateWithLongitude(lon: lon!,andLatitude: lat! ,andTitle: tit!)
}
let marker = GMSMarker(position: AppDelegate.getAppDelegate().myLocation)
let camera = GMSCameraPosition.camera(withLatitude: AppDelegate.getAppDelegate().myLocation.latitude, longitude: AppDelegate.getAppDelegate().myLocation.longitude, zoom: 11)
self.googleMapsView.camera = camera
marker.title = AppDelegate.getAppDelegate().sublocality
marker.map = self.googleMapsView
self.googleMapsView.animate(to: camera)
}
}
func locateWithLongitude(lon: Double, andLatitude lat: Double, andTitle title: String) {
DispatchQueue.main.async() { () -> Void in
let position = CLLocationCoordinate2DMake(lat, lon)
let marker = GMSMarker(position: position)
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 0)
self.googleMapsView.camera = camera
marker.title = title
marker.map = self.googleMapsView
}
}
Your zoom is set to 0, increase it to 15/16 like bellow.
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 16)
My problem is that when a jog has been completed, I can not present the recordedMapView with a full polyline that had tracked the location in an after exercise report.
Currently I am able to persist the data from tracking a run in the first view controller appearing in app, then in the detail view controller I fetch the data and unwrap/assign them to the respective variables, however, I am not sure where I go wrong in the code that is not allowing a polyline to appear. The map region does seem to be getting set properly as the map zooms in and out dynamically to fit the entire journey.
What could be the issue for why the polyline is not being presented and is there a solution to the code that I have provided to correct this problem?
var context : NSManagedObjectContext?
var runTimestamp : NSDate?
var runDuration : NSNumber?
var runDistance : NSNumber?
var runLocations : NSOrderedSet?
var locationTimeStamp : NSDate?
var locationLatitude : NSNumber?
var locationLongitude : NSNumber?
override func viewDidLoad()
{
super.viewDidLoad()
guard let context = context, finishedLocations = fetchLocation ( context ), finishedRun = fetchRun ( context ) else { return }
for location in finishedLocations
{
if let timestamp = location.timestamp, latitude = location.latitude, longitude = location.longitude
{
locationTimeStamp = timestamp
locationLatitude = latitude
locationLongitude = longitude
}
}
for run in finishedRun
{
if let timeStamp = run.timestamp, duration = run.duration, distance = run.distance, locations = run.locations
{
runTimestamp = timeStamp
runDuration = duration
runDistance = distance
runLocations = locations
}
}
updateUI ()
}
func loadMapView()
{
if runLocations!.count > 0
{
recordedMapView.region = mapRegion()
let colorSegments = MulticolorPolylineSegment.colorSegments(forLocations: runLocations!.array as! [Location])
recordedMapView.addOverlays(colorSegments)
}
else
{
let alertController = UIAlertController( title: "Error", message: "No Locations Saved", preferredStyle: .Alert )
let alertAction = UIAlertAction ( title: "Error", style : .Default , handler : nil )
alertController.addAction( alertAction )
presentViewController ( alertController, animated: true, completion: nil )
}
}
func mapRegion() -> MKCoordinateRegion
{
let initialLocation = runLocations!.firstObject as! Location
var minLat = initialLocation.latitude! .doubleValue
var minLng = initialLocation.longitude!.doubleValue
var maxLat = minLat
var maxLng = minLng
let locations = runLocations!.array as! [Location]
for location in locations
{
minLat = min( minLat, location.latitude! .doubleValue )
minLng = min( minLng, location.longitude!.doubleValue )
maxLat = max( maxLat, location.latitude! .doubleValue )
maxLng = max( maxLng, location.longitude!.doubleValue )
}
return MKCoordinateRegion(
center: CLLocationCoordinate2D( latitude : ( (minLat + maxLat)/2 ) , longitude : ( (minLng + maxLng)/2 ) ),
span : MKCoordinateSpan ( latitudeDelta: ( (maxLat - minLat)*1.1) , longitudeDelta: ( (maxLng - minLng)*1.1) )
)
}
func polyline() -> MKPolyline
{
var coordinates = [CLLocationCoordinate2D]()
let locations = runLocations!.array as! [Location]
for location in locations
{
coordinates.append( CLLocationCoordinate2D(latitude: (location.latitude!.doubleValue), longitude: (location.longitude!.doubleValue)) )
}
return MKPolyline(coordinates: &coordinates, count: runLocations!.count)
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer
{
let polyline = overlay as! MulticolorPolylineSegment
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.strokeColor = polyline.color
renderer.lineWidth = 3
return renderer
}
Swift 3.x:
What I see you don't add the polyLine properly into mapView.
Change your polyline function like below;
func polyline()
{
if theJourney != nil && theJourney!.coords != nil{
var coordinates = [CLLocationCoordinate2D]()
let locations = runLocations!.array as! [Location]
for location in locations
{
coordinates.append( CLLocationCoordinate2D(latitude: (location.latitude!.doubleValue), longitude: (location.longitude!.doubleValue)) )
}
}
let polyline = MKPolyline(coordinates: &coordinates, count: runLocations!.count)
mapView.add(polyline)
}
And MKMapView's rendererFor method with code below;
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.green
renderer.lineWidth = 3
return renderer
}
That's should work. Please let me know.
let latitude = NSUserDefaults.standardUserDefaults().doubleForKey(klat)
let longitude = NSUserDefaults.standardUserDefaults().doubleForKey(klong)
let location = CLLocationCoordinate2DMake(latitude, longitude)
// Second Location lat and long
let latitudeSec: CLLocationDegrees = 10.0100
let longitudeSec: CLLocationDegrees = 76.3620
let locationSec = CLLocationCoordinate2DMake(latitudeSec, longitudeSec)
let span = MKCoordinateSpanMake(1, 1)
let region = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: true)
I have two locations(lat and long) with two annotations. I need to know how to draw the line between these two annonations on MKMap?
Create an array of [CLLocationCoordinate2D], convert to MKPolyline and add to map.
If you have a CLLocation could get CLLocationCoordinate2D from CLLocation.coordinate
In your case...
let pointArry = [location, locationSec]
let myPolyline = MKPolyline(coordinates: pointArray, count: pointArray.count)
mapView.addOverlay(myPolyline)
//MARK: MKMapViewDelegate Method (make sure class has been set as delegate)
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: MKPolyline.self) {
// draw the track
let polyLine = overlay
let polyLineRenderer = MKPolylineRenderer(overlay: polyLine)
polyLineRenderer.strokeColor = UIColor.blue
polyLineRenderer.lineWidth = 2.0
return polyLineRenderer
}
return MKPolylineRenderer()
}
I'm trying to get an understanding of how to draw polylines using Swift. I've looked at the documentation, referenced some tutorials, and checked out some other SO posts, but I still can't get the thing to draw a line on my map. Here's my code. Anyone tell me what I'm doing wrong here?
import UIKit
import MapKit
class FirstViewController: UIViewController {
#IBOutlet weak var map: MKMapView!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let location = CLLocationCoordinate2D(
latitude: -73.761105,
longitude: 41.017791
)
let span = MKCoordinateSpanMake(0.07, 0.07)
let region = MKCoordinateRegion(center: location, span: span)
map.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.setCoordinate(location)
annotation.title = "White Plains"
annotation.subtitle = "Westchester County"
map.addAnnotation(annotation)
var locations = [CLLocation(latitude: -73.761105, longitude: 41.017791), CLLocation(latitude: -73.760701,longitude: 41.019348), CLLocation(latitude: -73.757201, longitude: 41.019267), CLLocation(latitude: -73.757482, longitude: 41.016375), CLLocation(latitude: -73.761105, longitude: 41.017791)]
var coordinates = locations.map({(location: CLLocation!) -> CLLocationCoordinate2D in return location.coordinate})
var polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
self.map.addOverlay(polyline)
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
}
Thanks!
Here MKGeodesicPolyline will solve your problem. Add object of MKGeodesicPolyline instead of MKPolyline.
In your code remove below two lines:
let polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
map.add(polyline)
And add these lines:
let geodesic = MKGeodesicPolyline(coordinates: coordinates, count: 2)
map.addOverlay(geodesic)
Swift 5.0:
func createPolyline(mapView: MKMapView) {
let point1 = CLLocationCoordinate2DMake(-73.761105, 41.017791);
let point2 = CLLocationCoordinate2DMake(-73.760701, 41.019348);
let point3 = CLLocationCoordinate2DMake(-73.757201, 41.019267);
let point4 = CLLocationCoordinate2DMake(-73.757482, 41.016375);
let point5 = CLLocationCoordinate2DMake(-73.761105, 41.017791);
let points: [CLLocationCoordinate2D]
points = [point1, point2, point3, point4, point5]
let geodesic = MKGeodesicPolyline(coordinates: points, count: 5)
map.addOverlay(geodesic)
UIView.animate(withDuration: 1.5, animations: { () -> Void in
let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
let region1 = MKCoordinateRegion(center: point1, span: span)
self.map.setRegion(region1, animated: true)
})
}
Objective C code:
- (void) createGeoPolyline {
CLLocationCoordinate2D point1 = { -73.761105, 41.017791 };
CLLocationCoordinate2D point2 = { -73.760701, 41.019348 };
CLLocationCoordinate2D point3 = { -73.757201, 41.019267 };
CLLocationCoordinate2D point4 = { -73.757482, 41.016375 };
CLLocationCoordinate2D point5 = { -73.761105, 41.017791 };
CLLocationCoordinate2D points[] = {point1, point2, point3, point4, point5};
MKGeodesicPolyline *geodesic = [MKGeodesicPolyline polylineWithCoordinates:&points[0] count:5];
[self.mapView addOverlay:geodesic];
[UIView animateWithDuration:1.5 animations:^{
MKCoordinateRegion region;
region.center = point1;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
[self.mapView setRegion:region animated:YES];
}];
}
Above Objective C code works perfect and it will show overlay below:
But if you try Swift code it will not. I tried as much as I can to solve it out but It won't change. May be it is bug from MapKit framework.
UPDATE: This seems to be fixed on Swift 3+. See accepted answer.
On this line:
var polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
You're casting a Swift array reference as an UnsafePointer<CLLocationCoordinate2D>.
That's pretty dangerous and I'm not sure why Swift allows it to compile. Best case scenario you get the line drawn, worse case (which seems to be your case) you get nothing.
The MKPolyline constructors wants an UsafePointer<CLLocationCoordinate2D> and that's what you should pass.
I usually add a private category to MKPolyline to create a convenience init method that accepts a normal Swift array:
private extension MKPolyline {
convenience init(coordinates coords: Array<CLLocationCoordinate2D>) {
let unsafeCoordinates = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(coords.count)
unsafeCoordinates.initializeFrom(coords)
self.init(coordinates: unsafeCoordinates, count: coords.count)
unsafeCoordinates.dealloc(coords.count)
}
}
Create polyline on apple map :
import MapKit
import CoreLocation
<CLLocationManagerDelegate,MKMapViewDelegate>
Code
self.mapView.delegate = self
var coordinateArray: [CLLocationCoordinate2D] = []
let destination1 = CLLocationCoordinate2DMake(22.3039, 70.8022)
let destination2 = CLLocationCoordinate2DMake(23.0225, 72.5714)
coordinateArray.append(destination1)
coordinateArray.append(destination2)
let polygon = MKPolyline(coordinates: coordinateArray, count: coordinateArray.count)
self.mapView.addOverlay(polygon)
Delegate Method
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: MKPolyline.self){
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.fillColor = UIColor.blue
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 2
return polylineRenderer
}
return MKOverlayRenderer(overlay: overlay)
}