Can i change pointer(MGLPointAnnotation) image in mapbox swift - ios

Hello I'm working on Mapbox I getting data from API and I am showing that data on the map but I want to show the default pointer to the image I'm getting from API can anybody help me
for locationStruct in self.locations
{
let annotation = MGLPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: Double(locationStruct.latitude) ?? 0.0, longitude: Double(locationStruct.longitude) ?? 0.0)
annotation.title = locationStruct.name
//Getting image
let url = URL(string:"http://app.freewayfinder.com/assets/uploads/spots/\(locationStruct.img)")
//Convert image in to data
let data = (try? Data(contentsOf: url!))!
self.mapview.addAnnotation(annotation)
}
this is code where I'm showing pointer's in map

Related

MapKit: How to update the polyline on the map upon the movement of one of the annotations

I am working on an app like Uber. I succeeded in drawing the line between the user and the driver on the map but I want also to track the driver movements, how to update the polyline according to driver moves.
Note: I have an API that I can get the current location of the driver.
let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlaceMark)
let destinationItem = MKMapItem(placemark: destinationPlaceMark)
let sourceAnotation = MKPointAnnotation()
sourceAnotation.title = sourceAddress
if let location = sourcePlaceMark.location {
sourceAnotation.coordinate = location.coordinate
}
let destinationAnotation = MKPointAnnotation()
destinationAnotation.title = destinationAddress
if let location = destinationPlaceMark.location {
destinationAnotation.coordinate = location.coordinate
}
mapView.showAnnotations([sourceAnotation, destinationAnotation], animated: true)
let directionRequest = MKDirections.Request()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationItem
directionRequest.transportType = .automobile
let direction = MKDirections(request: directionRequest)
direction.calculate { (response, error) in
guard let response = response else {
if let error = error {
print("ERROR FOUND : \(error.localizedDescription)")
}
return
}
let route = response.routes[0]
mapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads)
You already have the most important part working, getting driver's location, and drawing a route to it.
Now, you can simply run a timer and periodically perform following steps:
get driver location
check if new location is different (beyond some threshold) from previous location
calculate new route with updated location
remove old route polyline overlay
add new route polyline overlay

What is wrong with this code? When it opens up in the native maps app it takes me to a random location

Followed a video tutorial. When i build this app and hit the directions button it takes me to a random area instead of the coordinates provided. I am a beginner. Also, is there a way to pass in the locations address instead of coordinates, or should i just use the coordinates. Thanks for any responses. I am using Swift 5 in xCode 10. I changed the coordinate for privacy.
#IBAction func directionsClinic(_ sender: UIButton) {
let latitude:CLLocationDegrees = 38.465492
let longitude:CLLocationDegrees = 91.338905
let regionDistance:CLLocationDistance = 1000;
let coordinates = CLLocationCoordinate2DMake(latitude,
longitude)
let regionSpan = MKCoordinateRegion(center: coordinates,
latitudinalMeters: regionDistance, longitudinalMeters:
regionDistance)
let options = [MKLaunchOptionsMapCenterKey:
NSValue(mkCoordinate:regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan:
regionSpan.span)]
let placemark = MKPlacemark(coordinate: coordinates)
let mapItem = MKMapItem(placemark:placemark)
mapItem.openInMaps(launchOptions: options)
}
i have just tried a few different youtube videos guides, but most were a year+ old and im not sure if the code has changed
Expected the location of the coordinates to show up in the native iphone maps app, instead it was taking me to a place on the other side of the globe.
You can try this to open with a specific address:
let baseUrl: String = "http://maps.apple.com/?q="
let encodedName = theAddress.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) ?? ""
let finalUrl = baseUrl + encodedName
if let url = NSURL(string: finalUrl) {
UIApplication.shared.open(url)
}
The Maps app will intercept the request and open the app.

How can I add Multiple Markers on google map using json and swift 4.1?

Multiple marker doesn't show on google map using swift 4.1 i am connect JSON and result show on console but how can I connect with latitude and longitude with Google maps.
let jsonUrl = URL(string: "http://assetlinkasia.no-ip.biz:8001/hf_tracker/api/userdevices.php?accesskey=12345&user_id=1")
if let url = jsonUrl {
let data = NSData(contentsOf: url)
if let data = data {
do{
let jsonObject = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
if let object = jsonObject as? [NSString: AnyObject]{
if let allDevices = object["data"] as? [[NSString: AnyObject]]{
print("Successfull")
print(allDevices)
}
}
}catch{
print("Error Eccurred")
}
}
}
and this is my google map code here:
let getLongijson = Double("67.0011")
let getlatijson = Double("24.8607")
let camera = GMSCameraPosition.camera(withLatitude: getlatijson!, longitude: getLongijson!, zoom: 13.0)
let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
self.view = mapView
// meanView.addSubview(mapView)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: getlatijson!, longitude: getLongijson!)
marker.infoWindowAnchor = CGPoint(x:0.10, y:0.10)
marker.title = HeadingName
marker.snippet = Countory
marker.icon = UIImage(named: "markers")
marker.map = mapView
//User Location
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
// self.menuFunction()
mapView.delegate = self
Try this one
Objective-c
count = (int)locatorObject.LocationList.count;
for(int i=0;i< count;i++)
{
LocationDetails *locator = locatorObject.LocationList[i];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([locator.Lat floatValue],[locator.Long floatValue]);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.title = locator.Address;
marker.map = _googleMapView;
}
swift
for i in 0..<count {
var locator: LocationDetails? = locatorObject.locationList[i]
var position: CLLocationCoordinate2D = CLLocationCoordinate2DMake(locator?.lat, locator?.long)
var marker = GMSMarker(position: position)
marker.title = locator?.address
marker.map = googleMapView
}

iOS - Generate map image for the latitude and longitude

I have searched the internet but couldn't find if I can get the map image from the latitude and logitude.
Is there any api which can give me the map image .
Because I got start location and end location.
When I give the start and end location , it should give me map image with route .
Is the possible .
If I am on mapview I can manage snapshot , but here I won't have any mapview.
Any links, ideas , suggestions highly appreciated.
Regards.
I don´t know if there are any API´s available for this, but when I do this I just call the Apple Maps app and provide a latitude and longitude for my position and open up that app.
In that way the user can use the Apple Maps application to navigate and get full information about roads etc.
Here is how I call this:
func navigateWithAppleMaps(latitude: Double, longitude: Double) {
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "Start"
mapItem.openInMaps(launchOptions: options)
}
I think you have to use google developer static map api for this
https://developers.google.com/maps/documentation/static-maps/intro
You can get image from just passing latitude and longitude from following code. You can set zoom on mapview in URL.
var staticMapUrl: String = "http://maps.google.com/maps/api/staticmap?markers=color:red|\(YOUR LATITUDE HERE),\(YOUR LONGITUDE HERE)&\("zoom=16&size=400x400")&sensor=true"
var mapUrl = URL(string: staticMapUrl.addingPercentEscapes(using: String.Encoding.utf8))
var image = UIImage(data: Data(contentsOf: mapUrl))
SWIFT 5 creating two pins on map and path between them
Lets first get path between 2 points using google api:
//=== get points ===
var encodedPathPoints = "" //we'll get this from google api
let pointsUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=\(location1.lat!),\(location1.long!)&destination=\(location2.lat!),\(location2.long!)&sensor=false&mode=driving&key=\(ServiceConstants.MAP_KEY)"
if Reachability.isConnectedToNetwork(){
AF.request(pointsUrl).responseJSON { response in
let json = try? JSON(data: response.data!)
if json != nil {
print("JSON map results: \(json)")
let routes = json!["routes"].arrayValue
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
if points != nil {
encodedPathPoints = points!
}
}
}
}
}
Once i have path between my two points let set static map image
let MAP_BASE_URL = "https://maps.googleapis.com/maps/api/staticmap?"
let MAP_IMAGE_SIZE = "size=\(2 * Int(imageView.frame.size.width))x\(2 * Int(imageView.frame.size.height))"
let MAP_MARKER = "&markers=icon:https://www.google.com|";//your icon url
let MAP_deliveryLocation = "\(location.lat!),\(location.long!)"
let MAP_WAYPOINT = "\(storeLocation.lat!),\(storeLocation.long!)"
let MAP_KEY = "&key=\(ServiceConstants.MAP_KEY)"
let MAP_STYLE = "&format=png&maptype=roadmap&style=element:geometry|color:0xf5f5f5&style=element:labels.icon|visibility:off&style=element:labels.text.fill|color:0x616161&style=element:labels.text.stroke|color:0xf5f5f5&style=feature:administrative.land_parcel|element:labels.text.fill|color:0xbdbdbd&style=feature:poi|element:geometry|color:0xeeeeee&style=feature:poi|element:labels.text.fill|color:0x757575&style=feature:poi.park|element:geometry|color:0xe5e5e5&style=feature:poi.park|element:labels.text.fill|color:0x9e9e9e&style=feature:road|element:geometry|color:0xffffff&style=feature:road.arterial|element:labels.text.fill|color:0x757575&style=feature:road.highway|element:geometry|color:0xdadada&style=feature:road.highway|element:labels.text.fill|color:0x616161&style=feature:road.local|element:labels.text.fill|color:0x9e9e9e&style=feature:transit.line|element:geometry|color:0xe5e5e5&style=feature:transit.station|element:geometry|color:0xeeeeee&style=feature:water|element:geometry|color:0xc9c9c9&style=feature:water|element:labels.text.fill|color:0x9e9e9e&size=480x360"
let PATH = "&path=color:0x11C856|weight:5|enc:\(encodedPathPoints)" //use 'enc:' if you're using encoded path just like me, you can ignore this if you're using normal lat lng points concatenated in string.
let mapStaticImgUrlStr = "\(MAP_BASE_URL)\(MAP_IMAGE_SIZE)\(PATH)&center=\(MAP_deliveryLocation)|\(MAP_WAYPOINT)\(MAP_MARKER)\(MAP_deliveryLocation)\(MAP_MARKER)\(MAP_WAYPOINT)\(MAP_STYLE)\(MAP_KEY)"
let url = URL(string: mapStaticImgUrlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
do {
let data = try NSData(contentsOf: url3!, options: NSData.ReadingOptions())
imageView.image = UIImage(data: data as Data)
} catch {
imageView.image = UIImage()
}

How to launch Maps app and start navigation

In my iOS app I have latitude and longitude (CLLocationCoordinate2D) of a place the user would like to reach. I want than, when the relative button is pressed, that Maps application is launched and that street navigation to that place is started too. How can I achieve that? My code up to now is:
#IBAction func launchMapsApp(sender:UIButton) {
if (sender == self.navButton) {
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: self.currentCoordinates, addressDictionary: nil))
mapItem.name = ""
//You could also choose: MKLaunchOptionsDirectionsModeWalking
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey: true]
mapItem.openInMapsWithLaunchOptions(launchOptions as? [String : AnyObject])
}
}
But with this the Maps app is simply launched and I simply see a map of my state (Italy) and nothing more happens. Maybe, because I have run in only in simulator?
Thanks to all
You were on the right track: This is my swift 2.0 code:
let latitude:CLLocationDegrees = xx.xxxxx
let longitude: CLLocationDegrees = xx.xxxxx
let regiondistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionspan = MKCoordinateRegionMakeWithDistance(coordinates, regiondistance, regiondistance)
let options = MKLaunchOptionsMapCenterKey:NSValue(MKCoordinate:regionspan.center),MKLaunchOptionsMapSpanKey:NSValue(MKCoordinateSpan:regionspan.span)]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapitem = MKMapItem(placemark: placemark)
mapitem.name = "Name you want"
mapitem.openInMapsWithLaunchOptions(options)
I hope my code gives you some insight.
Your original code looks about right. It's possible, as you said, that the issue was how you were using the simulator. You can set a simulated location via the Debug menu in the simulator (Location -> Custom).
To launch Maps and start navigation to a specific location (as opposed to just opening Maps with a marker at the desired location, as in the other answer), I use this (in Swift 3):
let coordinates = CLLocationCoordinate2DMake(destLatitude, destLongitude)
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapitem = MKMapItem(placemark: placemark)
let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
mapitem.openInMaps(launchOptions: options)
Hope this helps...

Resources