Swift loop through array - ios

I'm trying to loop through an array with coordinates and show markers on a map with this code:
for index in 0...3 {
let latitude: Double = latCoordinate.objectAtIndex(index) as! Double
let longitude: Double = longCoordinate.objectAtIndex(index) as! Double
let position = CLLocationCoordinate2DMake(latitude, longitude)
print([latitude],[longitude])
let marker = GMSMarker(position: position)
marker.title = "Hello World"
marker.map = self.mapView
}
But I just get one marker on the map, it should be 4. Why can't I see the other markers on the map?

Your code looks good for displaying the marker, but are you sure the coordinates are correct? - Just looked at the comments again and the issue is in how you're populating your array, if you only have one coordinate in your array then you're only going to see one marker on the map.
This code from my app adds all the coordinates to a GMSCoordinateBounds and then sets the GMSMapView camera to the bounds of all the coordinates - so everything should be visible on the displayed map.
func plotAll(){
let bounds = GMSCoordinateBounds.init()
for property in fetchedResultsController.fetchedObjects!
{
let capitalAsset : CapitalAsset = property as! CapitalAsset
let marker = GMSMarker.init()
marker.draggable = false
marker.snippet = capitalAsset.address
let location = CLLocationCoordinate2DMake(Double(capitalAsset.latitude!), Double(capitalAsset.longitude!))
marker.position = location
marker.map = mapView
// Update bounds to include marker
bounds.includingCoordinate(marker.position)
}
let camera = mapView.cameraForBounds(bounds, insets:UIEdgeInsetsZero)
mapView.camera = camera;
}
Hope that helps.

Related

Google Map Swift SDK - how to combine fitbounds and center user location?

What I'm attempting to do is run fitbounds on a set of markers, which works perfectly. However, I would like to center the map based on the user's location while keeping all markers within the map view. But I haven't found a solution. Is it possible? below is my code currently use to fit bounds.
func focusMapToShowAllMarkers() {
var bounds = GMSCoordinateBounds()
for location in locationsArray
{
let latitude = location.position.latitude
let longitude = location.position.longitude
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude:latitude, longitude:longitude)
//marker.map = self.viewMap
bounds = bounds.includingCoordinate(marker.position)
}
//bounds = bounds.includingCoordinate(CLLocationCoordinate2D(latitude:latitude, longitude:longitude))
let update = GMSCameraUpdate.fit(bounds, withPadding: 10)
viewMap.animate(with:update)
}

How to check and load coordinate into Google Map (iOS)?

I have a list of coordinates in database, but i would like to load only the coordinates that currently in the view of Google Map and add a marker onto it. How can i do that ?
Once you get latitude and longitude, you can use the following function to add map marker and zoom to marker location :
func showMapMarker() {
self.currentLocationMapView.clear()
DispatchQueue.main.async {
let position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let marker = GMSMarker(position: position)
let bounds: GMSCoordinateBounds = GMSCoordinateBounds(coordinate: position, coordinate: position)
marker.title = "Snippet Title"
marker.map = self.currentLocationMapView
marker.snippet = "Snippet Text"
let camera = self.currentLocationMapView.camera(for: bounds, insets: UIEdgeInsets())
self.currentLocationMapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
self.currentLocationMapView.camera = camera!
}
}

Swift 3: Google maps not setting markers in for loop

I have been trying to add multiple markers to google map using for loop but it does not add to the google map. Adding one marker works or if writing code for each marker without for loop.
Declaration
#IBOutlet weak var googleMapView: GMSMapView! // set in story board
var shopsLatLong = [Double: Double]() // shops dictionary for lat long
For loop not working:
for (key,value) in shopsLatLong{
//Setting camera
self.googleMapView.camera = GMSCameraPosition.camera(withLatitude: key, longitude: value, zoom: 6.0)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(key, value)
marker.title = "Store Name"
marker.snippet = "Pakistan"
marker.map = self.googleMapView
print("Marker is \(marker)")
}
How to get this working? Kindly help me in figuring out this issue
Don't make class variable for marker. You have to create a local variable for the marker.
If you create a class variable then you will get only one marker. Because you are overriding the values inside the for loop
for (key,value) in shopsLatLong{
//Get the latitude and longitude of the marker and pass it here.
let lat = //latitude for marker
let lon = //longitude for marker
var marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(lat, lon)
marker.title = "Store Name"
marker.snippet = "Pakistan"
marker.map = self.googleMapView
}
First Create a array like
func setData(){
//create dictionary and store in mai array
var dicMapData : NSMutableDictionary = NSMutableDictionary()
dicMapData["title"] = "Kalasagar Shopping Hub"
dicMapData["image"] = "background9"
dicMapData["subtitle"] = "ShoppingHub"
dicMapData["latitude"] = 23.0669 // store latitude for specigic location
dicMapData["longitude"] = 72.5328 // store longitude for specigic location
arrMultipleAnotation.add(dicMapData)
dicMapData = NSMutableDictionary()
dicMapData["title"] = "Satadhar Cross Road"
dicMapData["image"] = "background8"
dicMapData["subtitle"] = "Crossroad"
dicMapData["latitude"] = 23.0629
dicMapData["longitude"] = 72.5328
arrMultipleAnotation.add(dicMapData)
dicMapData = NSMutableDictionary()
dicMapData["title"] = "Sola Bridge"
dicMapData["image"] = "menu-icon"
dicMapData["subtitle"] = "Bridge"
dicMapData["latitude"] = 23.0695
dicMapData["longitude"] = 72.5232
arrMultipleAnotation.add(dicMapData)
let initialLocation = CLLocation(latitude: 23.0669, longitude: 72.5289)
centerMapOnLocation(location: initialLocation)
//For Displayig Multiple Pin in mapview using array and loop
for locations in arrMultipleAnotation{
//Setting camera
self.googleMapView.camera = GMSCameraPosition.camera(withLatitude: dicCurrent["latitude"] as! Double, longitude: dicCurrent["longitude"] as! Double, zoom: 6.0)
self.marker = GMSMarker()
self.marker.position = CLLocationCoordinate2D(latitude: dicCurrent["latitude"] as! Double, longitude: dicCurrent["longitude"] as! Double)
self.marker.title = dicCurrent["title"] as? String
self.marker.snippet = dicCurrent["subtitle"] as? String
self.marker.map = self.googleMapView
print("Marker is \(self.marker)")
}
I hope It's work for you
I also had a similar issue and I was able to figure it out. Actually I wasn't overriding prepare for segue and the button was also directly linked to the storyboard due to which my view presented it self first before I even got the data. So here is what I did maybe it works for you too.
Override prepare for segue and set the variables there
Remove the segue link (if any) which is linking directly with the button
Add new segue from the top of the view controller to the new segue.
Build and Run.
I hope it resolves the issue for you too.
Change This code..
#IBOutlet weak var googleMapView: GMSMapView! // set in story board
var shopsLatLong = [Double: Double]() // shops dictionary for lat long
for (key,value) in shopsLatLong{
//Setting camera
self.googleMapView.camera = GMSCameraPosition.camera(withLatitude: key, longitude: value, zoom: 6.0)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(key, value)
marker.title = "Store Name"
marker.icon = image
marker.snippet = "Pakistan"
marker.map = self.googleMapView
print("Marker is \(self.marker)")
}
You should use a markers property, which is an array, and add your markers to this array. That way there will be a strong reference to all of your marker objects and you can easily work with them.
Also, a dictionary isn't really a good data structure for this purpose. I would suggest an array of struct where the struct has a latitude and longitude or even an array of tuples of (Double,Double)
#IBOutlet weak var googleMapView: GMSMapView! // set in story board
var shopsLatLong = [(Double,Double)]() // shops dictionary for lat long
var markers = [GMSMarker]()
for (position) in shopsLatLong{
//Setting camera
self.googleMapView.camera = GMSCameraPosition.camera(withLatitude: position.0, longitude: position.1, zoom: 6.0)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(position.0, position.1)
marker.title = "Store Name"
marker.snippet = "Pakistan"
marker.map = self.googleMapView
self.markers.append(marker)
print("Marker is \(marker)")
}

How to load google map polyline view in tableview cell?

I am using google's direction api to get all the Route information. From the response i am passing value of "overview_polyline" to the GMSPath object. Unfortunately it's not showing map . I have applied same logic in previous screen and its loading polyline perfectly. Are my cell's initialized before map loads?
let camera = GMSCameraPosition.camera(withLatitude: searchLocation.coordinate.latitude,
longitude: searchLocation.coordinate.longitude, zoom: 8)
let mapView = GMSMapView.map(withFrame: cell.viaMap.frame, camera: camera)
let center = CLLocationCoordinate2D(latitude: MomentaryLatitude, longitude: MomentaryLongitude)
mapView.isMyLocationEnabled = true
cell.viaMap.addSubview(mapView)
let marker = GMSMarker()
marker.title = "Current Location"
marker.snippet = "XXX"
marker.map = cell.viaMap
let path: GMSPath = GMSPath(fromEncodedPath: myPolyLine)!
let routePolyline = GMSPolyline(path: path)
routePolyline.map = cell.viaMap
routePolyline.strokeWidth = 50
routePolyline.strokeColor = UIColor.red
routePolyline.map = cell.viaMap
var bounds = GMSCoordinateBounds()
let pathInt = Int((path.count()))
for i in 0 ..< pathInt{
bounds = bounds.includingCoordinate(path.coordinate(at: UInt(i)))
}
cell.viaMap.animate(with: GMSCameraUpdate.fit(bounds))

How to set visible region/zoom level for google maps IOS to show all markers added to the mapview

I have used Google maps in ios app, I wanna set zoom level dynamically depends on the search i made over map. Basically am adding pins by searching with city names or lat/long query. after every search am adding pins & i need to show all added markers by the recent search i made.
#IBOutlet weak var mapView: GMSMapView!
let camera = GMSCameraPosition.cameraWithLatitude(23.0793, longitude:
72.4957, zoom: 5)
mapView.camera = camera
mapView.delegate = self
mapView.myLocationEnabled = true
*** arry has dictionary object which has value of Latitude and Longitude. ***
let path = GMSMutablePath()
for i in 0..<arry.count {
let dict = arry[i] as! [String:AnyObject]
let latTemp = dict["latitude"] as! Double
let longTemp = dict["longitude"] as! Double
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latTemp, longitude: longTemp)
marker.title = "Austrilia"
marker.appearAnimation = kGMSMarkerAnimationNone
marker.map = self.mapView
path.addCoordinate(CLLocationCoordinate2DMake(latTemp, longTemp))
}
let bounds = GMSCoordinateBounds(path: path)
self.mapView!.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 50.0))
See this answer for a simple way to iterate over a given array of markers and then set the bounds accordingly.

Resources