We are coding in Swift to create an application with UI buttons. These UI buttons will add or remove markers depending on its status. Because we want the buttons to be layered on top of google maps we have two view controllers. The top view controller contains a button. When the button is pressed, we want to remove the markers that have a "bad" status.
This is our code to remove the marker:
func showOnlyGood(){
mapView.clear() //this is the google map (GMSMapView.map)
for x in arrayOfGood { //Array of good markers
x.map = mapView //Set good markers to show
}
for y in arrayOfBad { //Array of bad markers
y.map = nil //removes markers from map
}
}
The google maps gets updated if the function call is in viewDidLoad(), but when we call the function in the top view controller with the buttons it does not update the map accordingly.
We think this is an issue with refreshing the google map view and have tried many different solutions, but the google map view only shows what is initially in viewDidLoad().
First, if you just want the buttons to be layered on top of the map, just add the buttons to the view after you've added the map to the view; do not create a second view controller. Your problem is most likely caused by this awkward setup. You also don't have an #objc prefix in your action method, which would definitely prevent the button from executing its action.
#objc func updateButtons() {
mapView.clear() // clear the map
for i in someArray {
let marker = GMSMarker()
// configure parameters
marker.map = mapView
}
}
That method will update your map's markers. There is [probably] never a need to refresh the map, even if you want to change styles.
Related
In the code posted, when you click on the annotation, the speech balloon pops up to say
Hello World!
Welcome to my marker
I would like to know how to make the speech bubble appear while using the app, and have the speech bubble display some text that the user would enter in, and disappear after about an hour or so. The bubble would be able to be seen by other users even if the user logged out or closed the app, and the bubble would still be open when the user goes back into the app, unless the window of time for the bubble has passed.
Thank-you
import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Set the map’s center coordinate and zoom level.
mapView.setCenter(CLLocationCoordinate2D(latitude: 40.7326808, longitude: -73.9843407), zoomLevel: 12, animated: false)
view.addSubview(mapView)
// Set the delegate property of our map view to `self` after instantiating it.
mapView.delegate = self
// Declare the marker `hello` and set its coordinates, title, and subtitle.
let hello = MGLPointAnnotation()
hello.coordinate = CLLocationCoordinate2D(latitude: 40.7326808, longitude: -73.9843407)
hello.title = "Hello world!"
hello.subtitle = "Welcome to my marker"
// Add marker `hello` to the map.
mapView.addAnnotation(hello)
}
// Use the default marker. See also: our view annotation or custom marker examples.
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}
// Allow callout view to appear when an annotation is tapped.
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
}
Are you wanting the user to enter text into a text field inside the annotation bubble? If so, consider subclassing MGLPointAnnotation and adding a text field to it. That might be a bit tricky though since it would appear that MGLPointAnnotation is a subclass of MGLShape, which appears to not be a subclass of the usual UIKit hierarchy of view/view-controller classes. You may be better off swapping out the Mapbox framework for a basic MapKit solution (...I don't know for what else you are relying on Mapbox though).
Apple's MapKit does have MKAnnotationView. There is a definite answer for how to add a UITextField to MKAnnotationView. See how to add UITextField in MKAnnotationView Title. You may need to modify the answer depending on how you want your annotation to behave.
If, on the other hand, you were thinking of the user entering text into a text field through another screen in the iOS app, there are many easy ways to properly implement a UITextField in a UIViewController, UIView, UITableViewController, UICollectionView, etc.
Alternatively, if you were thinking about the user entering text through a website, that is trivially easy with HTML forms.
For the approximate 1 or 3 hour(s) timeframe for displaying the bubble before it goes away, you would need to add a createdTimestamp property to the MKAnnotationView subclass. Just compare the current time periodically to the createdTimestamp on the annotation and if currentTime >= annotation.createTimestamp + oneHour, remove the annotation from the map. You can see about dates in Swift here: https://developer.apple.com/documentation/foundation/date
As far as "other users" seeing the bubble goes, that would require some sort of networked solution (such as a central server that synchronizes with these bubbles' data and then broadcasts them to other users). You would need a networked setup anyway if you were thinking of using website(s) to gather/display map data.
Presumably from your other question, I assume that you are using the map fullscreen. There are several approaches to this.
You could use the default I accessory button to add a target action to it. Which calls a custom UIView which has a textView and a submit button. Which then modifies your annotation.
Or you could modify your mapview to show a small textbox at the bottom of the screen which is then shifted upwards whilst editing and added to your annotation upon submitting.
When it comes to your timeout question I did not find anything in the MapBox's documentation to get you the results you want. I believe it needs some sort of backend server side timer function which will handle this accordingly.
So this piece of code gets nearest searchedTypes(atms and banks) for google and puts markers around the map.
private func fetchNearbyPlaces(coordinate: CLLocationCoordinate2D) {
mapView.clear()
dataProvider.fetchPlacesNearCoordinate(coordinate, radius:searchRadius, types: searchedTypes) { places in
places.forEach {
let marker = PlaceMarker(place: $0)
marker.map = self.mapView
}
}
}
How do I get a table view with the list of these nearest searedTypes and get information on them to show on another viewcontroller where I can navigate from user location to that point. How the normal google maps works.
With places acquired, you can pass data to a new controller that has table view and display data there.
I need to know how to fetch the title of a dropped pin. I have multiple dropped pins on the map, when the pin is tabbed I want to fetch the title to pass to prepareForSegue. I use this statement "let title = self.pointAnnotation.title" via (MKPointAnnotation) but I get the title of the last dropped pin and not the tabbed pin.
An easy and reliable way to get a reference to the annotation that was tapped is to use the map view's selectedAnnotations array: if let ann = self.mapView.selectedAnnotations[0] as? MKAnnotation {
println("(ann.title!)")
}
I've got an array of places. Each of these places are displayed on a MapView and on a TableView on the same screen. I'd like to pop up the pin annotation of a place when I tap the corresponding row on the table view.
I've got the following code to populate annotations:
for (int i = 0; i < [self.myPlaces count]; i++)
{
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
SPlaces *ev = [self.myPlaces objectAtIndex:i];
point.coordinate = CLLocationCoordinate2DMake([ev.location.latitude doubleValue], [ev.location.longitude doubleValue]);
point.title = ev.title;
point.subtitle = ev.type.name;
[self.myMap addAnnotation:point];
}
and this code to display an annotation when a row is selected on the TableView:
//row = tapped row on TableView
[self.myMap selectAnnotation:[[self.myMap annotations] objectAtIndex:row] animated:YES];
The issue is that the annotations seems to have a random index in the myMap annotations array.
I mean, i'd like to have this behavior:
users taps row 0 on Table view => annotation of pin 0 pops up on the map
users taps row 1 on Table view => annotation of pin 1 pops up on the map
users taps row 2 on Table view => annotation of pin 2 pops up on the map
But instead of this, I get:
users taps row 0 on Table view => annotation of pin 1 pops up on the map
users taps row 1 on Table view => annotation of pin 0 pops up on the map
users taps row 2 on Table view => annotation of pin 2 pops up on the map
...or any other random combination that change each time I restart the app.
Note that if I enable user's location, one of my pin annotation can have it's title randomly changed for "Current location".
I'm pretty sure I'm note populating or accessing the annotation correctly. Do you have any clue ?
Thanks !
EDIT: This post seems to say that you have to scan your annotations array, looking for a matching title, then select the relevant annotation : Open Map Annotation from Selected Row in Table View
Is this really the only way ? Since two pins could possibly share the same title, it seems a little bit hazardous...
The map view's annotations array is not guaranteed to return the annotations in the order that you added them.
This is partly due to the fact that if you have showsUserLocation set to YES, the annotations array returned by the map view includes the user location annotation even though you didn't explicitly call addAnnotation on it yourself. The map view adds that annotation internally so you have no control over the order.
The other reason is simply that the documentation doesn't say the array will be in any particular order.
See MKMapView annotations changing/losing order? for some more details.
As the answer you linked to suggests, one option is to search the annotations array until you find the one you're looking for that matches the criteria.
If your annotations are of type MKPointAnnotation, the only properties available are title, subtitle, and coordinate.
If these don't work for you (eg. if you can have annotations with the same title), you'll need to use a custom annotation class that has a property unique to each annotation.
However, note that the annotation class does not have to be a different class from your underlying data model class (eg. SPlaces).
It can simplify matters if your SPlaces class implements the MKAnnotation protocol itself. Then:
You won't need to loop through self.myPlaces and create separate annotation objects. Instead, you would have just the single line [self.myMap addAnnotations:self.myPlaces];.
You won't need to search through the map view's annotations array to find your SPlaces object. Instead, in didSelectRowAtIndexPath, you would be able to just do this:
[self.myMap selectAnnotation:[self.myPlaces objectAtIndex:row]
animated:YES];
I have MKMapView with many annotations in proper order. And I have button to change map mode:
- (IBAction)userDidPressTrackButton:(id)sender {
if (self.mapView.userTrackingMode == MKUserTrackingModeFollow) {
self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
return;
}
if (self.mapView.userTrackingMode == MKUserTrackingModeFollowWithHeading) {
self.mapView.userTrackingMode = MKUserTrackingModeNone;
return;
}
if (self.mapView.userTrackingMode == MKUserTrackingModeNone) {
self.mapView.userTrackingMode = MKUserTrackingModeFollow;
}
}
when mode = MKUserTrackingModeFollowWithHeading annotations begin to put themselves in random order. It seems that in this mode mapview begin to redraw itself every second and put all the subview (annotations) in unknown order.
How to cancel changing order of annotations?
The array of annotations that you get back from mapview.annotations is not guaranteed to be in the same order you that added them in. If you are relying on them vein in a special order you are probably doing your viewForAnnotations function wrong. It is given an annotation as a parameter, you use that to determine what view to draw. Usually people make a custom class that implements the MKAnnotation protocol and has some addition variables in which they store the data needed to create the right view. When viewForAnnotations gets called they check if the provided annotation is one of their special class, and if so extract the data, make the view and return it. There is no need to know the order of the annotations array, and it wouldn't do you any good because an MKMapView can and will ask for the annotations in any sequence it likes.
Side note: Why are you writing your own function for toggling the tracking mode? You can just use the official one and it will do it all for you.