Pin correct Annotation Image parse backend - ios

I have setup a map in which data is loaded from the parse backend. In map I want to display the images that are already saved in Assets folder. Image should be equal to Player Name . There latitude and longitude is already saved in the Parse.
The position of the player is displayed correctly but the image is not being showed correctly , if the last name in the playerName column is Sachin then the image is same for all the player annotation pin.
I want to apply like if playerName == annotation.title the image of rahul should be displayed .
Console Print :
26.6481591686873 , 77.1777485870544 Sachin
27.655116868732 , 77.17778705437 Rahul
28.6479996556687 , 77.1779252453013 Matt
28.6480628887157 , 77.1779590059193 Virat
28.1578689896 , 76.989079 Sachin
var playerName:String!
override func viewDidLoad() {
super.viewDidLoad()
query.findObjectsInBackgroundWithBlock { (posts, error) in
if error == nil {
let myPosts = posts! as [PFObject]
for posts in myPosts {
let latitude12 = posts["playerLat"] as! Double
let longitude12 = posts["playerLong"] as! Double
let playName = posts["playerName"] as! String
self.playerName = posts["playerName"] as! String
print(latitude12,"," , longitude12, playerName)
let annotation = MKPointAnnotation()
//let customAnno = MKAnnotationView()
let locationCoordinate = CLLocationCoordinate2DMake(latitude12, longitude12)
annotation.coordinate = locationCoordinate
//customAnno.enabled = true
let anno = self.mapView.dequeueReusableAnnotationViewWithIdentifier("places")
if anno == nil {
// if annotation.title == "Sachin" {
//}
annotation.title = playerName
self.mapView.addAnnotations([annotation])
} else {
anno?.annotation = annotation
}
}
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "customAnnotationView"
let annotation1 = MKPointAnnotation()
// custom image annotation
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if (annotationView == nil) {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
}
else {
annotationView!.annotation = annotation
}
if annotation1.title == "Rahul" {
annotationView!.image = UIImage(named: "Rahul")}
else if annotation1.title == "Sachin"{
annotationView!.image = UIImage(named: "Sachin")
}
return annotationView
}
I have tried all codes but the image is same for all the players image.

Related

How to remove "trace" of a mark in swift

I'm working on a tracker app and I managed to pull some data from the server and update other user's so called track. But I have this mark .person, which appears on every step. How Should I remove it?
Polyline is drawn like this:
private func updateOnlineTrackOnMap() {
let locations = self.track?.points?.map { $0.location } ?? []
guard locations.count >= 2 else { return }
mapView.drawPolyline(withLocations: locations)
mapView.setMark(.person, to: locations.last!.coordinate)
}
But mapView.removeMark(.person) doesn't work.
Ok, there were some custom methods. I've managed to do the trick like so:
if let oldAnnotation = self.drawer.oldAnnotation {
mapView.removeAnnotation(oldAnnotation)
}
let annotation = MKPointAnnotation()
annotation.coordinate = locations.last!.coordinate
annotation.title = "Speed"
let speed = locations.last!.speed * 3.6
annotation.subtitle = String(format: "%.2f km/h", speed)
mapView.addAnnotation(annotation)
mapView.selectAnnotation(annotation, animated: false)
oldAnnotation = annotation
mapView.drawPolyline(withLocations: locations)
There's just a global variable to store current annotation coordinate. And then in mapView :viewFor: I wrote something like this:
if annotation is MKPointAnnotation {
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "Online")
annotationView.image = rotatedArrow
annotationView.canShowCallout = true
return annotationView
}

Associating different pin images with different locations iOS

I have an array of 4 locations, and an array of 4 pin names (ie "bluePin.png | redPin.png | etc...")
Currently I'm using a bit of code I found elsewhere to add custom pin graphics to all 4 locations, but all of my pins are red.
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let annotationReuseId = "Truck"
var trkPin = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
if trkPin == nil {
trkPin = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
} else {
trkPin!.annotation = annotation
}
trkPin!.image = UIImage(named: "redPin.png")
trkPin!.backgroundColor = UIColor.clearColor()
trkPin!.canShowCallout = false
return trkPin
}
How could I associate the pin colors with the locations in the array, so that each location is differentiated by color?
Thanks!
I have done this in the simple way by declaring array of location and array images. And I have viewDidLoad method as follows.
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
let location = [
CLLocationCoordinate2D(latitude: 12, longitude: 77),
CLLocationCoordinate2D(latitude: 12.5, longitude: 77.5),
CLLocationCoordinate2D(latitude: 13, longitude: 78),
CLLocationCoordinate2D(latitude: 13.5, longitude: 78)
]
let pins = [
"red.png",
"blue.png",
"green.png",
"yellow.png"
]
var annotations = [MKPointAnnotation]()
for (index, eachLocation) in location.enumerate() {
let pinImageName = pins[index]
let annotation = MKPointAnnotation()
annotation.coordinate = eachLocation
annotation.title = "\(pinImageName)"
annotations.append(annotation)
}
mapView.addAnnotations(annotations)
}
And in the viewForAnnotation delegate method just getting that image name from the title property and explicitly disabling the callout
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let annotationReuseId = "Truck"
var trkPin = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
if trkPin == nil {
trkPin = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
trkPin!.canShowCallout = false
} else {
trkPin!.annotation = annotation
if let image = annotation.title {
trkPin!.image = UIImage(named: image ?? "default.png")
} else {
trkPin!.image = UIImage(named: "default.png")
}
}
return trkPin
}

How to find location of a pinned item using MapKit and Swift

I used MapKit's localsearch feature to generate annotation pins of whatever was typed into a search bar. I am now having trouble finding the address of those pinned locations. this is my code for the local search
func performSearch() {
matchingItems.removeAll()
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchText.text;
request.region = attractionsMap.region;
let search = MKLocalSearch(request: request)
search.startWithCompletionHandler({(response:
MKLocalSearchResponse!,
error: NSError!) in
if error != nil {
println("Error occured in search: \(error.localizedDescription)")
} else if response.mapItems.count == 0 {
println("No matches found")
} else {
println("Matches found")
for item in response.mapItems as! [MKMapItem] {
println("Name = \(item.name)")
println("Phone = \(item.phoneNumber)")
matchingItems.append(item as MKMapItem)
println("Matching items = \(matchingItems.count)")
var annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
self.attractionsMap.addAnnotation(annotation)
}
}
})
}
This is my viewForAnnotation method:
extension AttractionsVC: MKMapViewDelegate {
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if(annotation is MKUserLocation) {
return nil;
}
let reuseId = "pin";
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView;
if(pinView == nil) {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId);
pinView!.canShowCallout = true;
pinView!.animatesDrop = true;
}
var moreInfoButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton;
pinView?.rightCalloutAccessoryView = moreInfoButton;
return pinView;
}
I would now like to be able to display the address on the annotation. Any thoughts would be greatly appreciated.
I still don't understand what it is you want. Sometimes you ask about the address, sometimes you ask about the location.
The location is the latitude and longitude
It is the annotation's coordinate property.
The address is the human postal address
When you called
let search = MKLocalSearch(request: request)
search.startWithCompletionHandler( // ...
...you got back MKMapItems:
for item in response.mapItems as! [MKMapItem] {
Inside each MKMapItem was a placemark (an MKPlacemark, the MKMapItem's placemark property). Inside each placemark was the address information — an MKPlacemark is a CLPlacemark, so consult the CLPlacemark document for how to extract the address info.
Well, you appended each MKMapItem to an array:
matchingItems.append(item as MKMapItem)
That's where the MKMapItems are, unless you've thrown them away; so that's where the address information is.

Attempting to change MKAnnotation color within my code?

So I have set up my MKAnnotations in MapView and it's working as I want it to. Now I would like to experiment further and try to change the colors of the pins, what would be the most efficient way to implement this within the following code:
override func viewDidAppear(animated: Bool) {
var annotationQuery = PFQuery(className: "Post")
currentLoc = PFGeoPoint(location: MapViewLocationManager.location)
//annotationQuery.whereKey("Location", nearGeoPoint: currentLoc, withinMiles: 10)
annotationQuery.whereKeyExists("Location")
annotationQuery.findObjectsInBackgroundWithBlock {
(points, error) -> Void in
if error == nil {
// The find succeeded.
println("Successful query for annotations")
// Do something with the found objects
let myPosts = points as! [PFObject]
for post in myPosts {
let point = post["Location"] as! PFGeoPoint
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude)
annotation.title = post["title"] as! String!
annotation.subtitle = post["username"] as! String!
func mapView(aMapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let reuseId = "pin"
var pinView = aMapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
println("Pinview was nil")
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.pinColor = .Green
return pinView
}
self.mapView.addAnnotation(annotation)
}
} else {
// Log details of the failure
println("Error: \(error)")
}
}
I can't seem to tackle this on my own even though it seem's simple enough. I am also confused about the viewForAnnotation method, from what I could gather it seems like i need to use it, but nothing i'm trying is working.
I know this is a late answer but for anyone else searching, check out the tutorial here which shows exactly how to colour pins
Ray Wenderlich MapView

Swift - setting different images from array to annotation pins

I wonder how to set different images to annotation pins on mapview. The difference between the following questions
viewForAnnotation confusion and customizing the pinColor iteratively
Swift different images for Annotation
is that my array of images is generated dynamically with regard to server response. There is no fixed size of the array, so switch/case construction is not a good idea. Moreover, I'm not sure how to apply the solution with custom class aforementioned in topic above. I'm aware that it would be better to post a comment to one of the questions asked before, but unfortunately I'm too rookie at the moment to do that(too few points).
This is the for loop performed inside functions that shows map:
for var r=0;r<arrayOfRestaurants.count;r++
{
var summonRestaurant:NSDictionary = arrayOfRestaurants[r] as NSDictionary
var nearbyRestaurant = Restaurant(nearbyRestaurants:summonRestaurant)
var latRestaurant=(nearbyRestaurant.latitude as NSString).doubleValue
var longRestaurant=(nearbyRestaurant.longitude as NSString).doubleValue
var locationOfRestaurant = CLLocationCoordinate2D(
latitude: latRestaurant as CLLocationDegrees, longitude: longRestaurant as CLLocationDegrees)
var lunchArray: NSArray = nearbyRestaurant.lunch as NSArray
var annotation = MKPointAnnotation()
annotation.setCoordinate(locationOfRestaurant)
annotation.title = nearbyRestaurant.name + " " + nearbyRestaurant.distance + " km"
map.addAnnotation(annotation)
}
And here is viewForAnnotation delegate method(quite identical to the method used in aforementioned threads):
func mapView(map: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = map.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.pinColor = .Purple
pinView!.image = globalImageArray[0]
}
else {
pinView!.annotation = annotation
}
return pinView
}
As you can see, I assigned a certain image to pinView which is globalImageArray[0], but I look for a solution that let me iterate over the globalImageArray and assign a certain image to each pin.
I'd be glad to receive any help, thanks in advance!
First, you need to create your own class that adopts the MKAnnotation protocol for your annotations -
class RestaurantAnnotation : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String
var subtitle: String
var image: UIImage?
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
Then, use instances of this class when you add the annotation and set the image -
for var r=0;r<arrayOfRestaurants.count;r++
{
var summonRestaurant:NSDictionary = arrayOfRestaurants[r] as NSDictionary
var nearbyRestaurant = Restaurant(nearbyRestaurants:summonRestaurant)
var latRestaurant=(nearbyRestaurant.latitude as NSString).doubleValue
var longRestaurant=(nearbyRestaurant.longitude as NSString).doubleValue
let locationOfRestaurant = CLLocationCoordinate2D(
latitude: latRestaurant as CLLocationDegrees, longitude: longRestaurant as CLLocationDegrees)
var lunchArray: NSArray = nearbyRestaurant.lunch as NSArray
let title = nearbyRestaurant.name + " " + nearbyRestaurant.distance +" km"
var annotation = RestaurantAnnotation(coordinate, title:title, subtitle:"")
annotation.image = globalImageArray[r]
map.addAnnotation(annotation)
}
Now, in your view for annotation you can access the image -
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if !(annotation is RestaurantAnnotation) {
return nil
}
let reuseId = "restaurant"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
let restaurantAnnotation = annotation as RestaurantAnnotation
if (restaurantAnnotation.image != nil) {
anView.image = restaurantAnnotation.image!
anView.image.layer.setCornerRadius(8.0)
anView.image.layer.clipsToBounds=true
}
else {
// Perhaps set some default image
}
return anView
}

Resources