I want to remove d polyline in google map , but it remain I have try everything as you can see from the code also I check the debug area and the rectangle.map is nil?? but it still appear on the map and I do not want to user the clear method is work correct but I have other element on the map that I dint want to remove
DispatchQueue.main.async {
let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
let rectangle = GMSPolyline(path: path)
var oldPolylineArr = [GMSPolyline]()
oldPolylineArr.append(rectangle)
if self.count == 0 {
rectangle.map = self.googelMap
print("count \(self.count)")
self.count = 1
}
else if self.count == 1 {
//rectangle.map = nil
//path.removeAllCoordinates()
self.count = 0
for p in (0 ..< oldPolylineArr.count) {
oldPolylineArr[p].map = nil
}
}
}
}
This is local variable ( Inside the function )
var oldPolylineArr = [GMSPolyline]()
oldPolylineArr.append(rectangle)
you need to make it an instance var , as it holds the last one , so get this line out
var oldPolylineArr = [GMSPolyline]()
Then to clear all do
oldPolylineArr.forEach { $0.map = nil }
after that set your new created polyline
rectangle.map = self.googelMap
This will add a polyline and remove the old
class ViewController:UIViewController {
var oldPolylineArr = [GMSPolyline]()
override func viewDidLoad() {
super.viewDidLoad()
}
func addPolyAndRemoveOld() {
DispatchQueue.main.async {
// remove here
oldPolylineArr.forEach { $0.map = nil }
// add new
let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
let rectangle = GMSPolyline(path: path)
oldPolylineArr.append(rectangle)
rectangle.map = self.googelMap
}
}
}
Related
I have encountered a strange problem, when i zoom out the my polyline of custom coordinates starts disappearing, following is my code
func setTrackerLines(currentLoc: String, destinationLoc: String) {
let str1 = currentLoc
let LocArray1 = str1.components(separatedBy: ",")
let str2 = destinationLoc
let LocArray2 = str2.components(separatedBy: ",")
let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: (LocArray1[0] as NSString).doubleValue, longitude: (LocArray1[1] as NSString).doubleValue))
path.add(CLLocationCoordinate2D(latitude: (LocArray2[0] as NSString).doubleValue, longitude: (LocArray2[1] as NSString).doubleValue))
let rectangle = GMSPolyline(path: path)
rectangle.strokeColor = UIColor.blue
rectangle.strokeWidth = 1
rectangle.map = self.myMapView
}
}
have call this method on viewdidload(), This is how i am using the code
for i in 0 ..< pointArray.count {
print("Delta: \(delta)")
if pointArray.count != (i + 1) {
self.setTrackerLines(currentLoc: pointArray[i], destinationLoc: pointArray[i + 1])
}
The result is showing in pictures. Kindly help please
I try to use reverseGeocoordinate to show the address from locationEnd at my DestinationSearchBar but i don't know how to do it.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude, longitude: place.coordinate.longitude, zoom: 15.0)
if locationSelected == .startLocation {
addressSearchBar.text = "\(place.coordinate.latitude), \(place.coordinate.longitude)"
locationStart = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
createMarker(titleMarker: "Punto de recojo", iconMarker: #imageLiteral(resourceName: "marker"), latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
} else {
DestinationSearchBar.text = "\(place.coordinate.latitude), \(place.coordinate.longitude)"
locationEnd = CLLocation(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
createMarker(titleMarker: "Punto de destino", iconMarker: #imageLiteral(resourceName: "marker"), latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
self.mapView.camera = camera
self.dismiss(animated: true, completion: nil)
}
}
Apple providing reverse geo location api
let address = CLGeocoder.init()
address.reverseGeocodeLocation(CLLocation.init(latitude: latitude, longitude:longitude)) { (places, error) in
if error == nil{
if let place = places{
//here you can get all the info by combining that you can make address
}
}
}
and don't forget imports
import MapKit
import CoreLocation
I want to redraw my direction path and move my marker to the current location. I am currently doing this inside didUpdateLocations function but it gets glitchy because it draws multiple markers and path at the same time.
Here is my code:
let location = locations.last
let destination = CLLocation(latitude: order!.user_coord![0], longitude: order!.user_coord![1])
let origin = CLLocation(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
self.drawPath(startLocation: origin, endLocation: destination)
self.createMarker(titleMarker: order!.store_name!, iconMarker: UIImage(named: "icons8-user_filled")!, latitude: order!.user_coord![0], longitude: order!.user_coord![1])
self.createMarker(titleMarker: "User", iconMarker: UIImage(named: "icons8-mountain_biking")!, latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)
self.map.animate(to: camera)
locationManager.stopUpdatingLocation()
Declare a variable
var drawFinished:Bool!
in viewDidLoad
drawFinished = false
in didUpdate
if(!drawFinished)
{
drawFinished = true
let location = locations.last
let destination = CLLocation(latitude: order!.user_coord![0], longitude: order!.user_coord![1])
let origin = CLLocation(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
self.drawPath(startLocation: origin, endLocation: destination)
self.createMarker(titleMarker: order!.store_name!, iconMarker: UIImage(named: "icons8-user_filled")!, latitude: order!.user_coord![0], longitude: order!.user_coord![1])
self.createMarker(titleMarker: "User", iconMarker: UIImage(named: "icons8-mountain_biking")!, latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)
self.map.animate(to: camera)
locationManager.stopUpdatingLocation()
}
when you want to update set
drawFinished = false
and clear paths and annotations like this
func clearMapOverlays()
{
for dl in self.myMapView.overlays
{
if(dl is GMSPolyline )
{
self.myMapView.remove(dl)
}
}
self.myMapView.setNeedsDisplay()
for name in self.myMapView.annotations
{
self.myMapView.removeAnnotation(anno)
}
}
I'm using Google PlacePicker API in my iOS application using Swift 3.0.
I need 13 digits of precision after the decimal. But Google PlacePicker is returning latitude and longitude with 7 digits after the decimal.
Below is my function:
func pickPlace(sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
let northEast = CLLocationCoordinate2D(latitude: center.latitude + 0.001, longitude: center.longitude + 0.001)
let southWest = CLLocationCoordinate2D(latitude: center.latitude - 0.001, longitude: center.longitude - 0.001)
let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let config = GMSPlacePickerConfig(viewport: viewport)
let placePicker = GMSPlacePicker(config: config)
placePicker.pickPlace(callback: {(place, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
if let place = place {
let coordinates = CLLocationCoordinate2DMake(place.coordinate.latitude, place.coordinate.longitude)
let marker = GMSMarker(position: coordinates)
marker.title = place.name
marker.map = self.googleMapView
self.googleMapView.animate(toLocation: coordinates)
let geoCode = "\(place.coordinate.latitude),\(place.coordinate.longitude)"
self.showGeoSelector(title: "Selected Coordinates", message: "Latitude: " + String(place.coordinate.latitude) + " Longitude: " + String(place.coordinate.longitude), geoCode: geoCode, geoLat: String(place.coordinate.latitude), geoLong: String(place.coordinate.longitude))
}
})
}
Try this code:
let geoCode = "\(String(format: "%.18f", place.coordinate.latitude)),\(String(format: "%.18f", place.coordinate.longitude))"
Hope its helps :)
I want to know how to pin annotations randomly in a MapView
let latitude: CLLocationDegrees = 33.606800
let longitude: CLLocationDegrees = -111.845360
let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
//map annotation
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "Taliesin West"
annotation.subtitle = "Design"
map.addAnnotation(annotation)
For Anyone who wants the solution:
First: Adding Random Annotation according to current Location
Generating the Annotations:
func generateAnnoLoc() {
var num = 0
//First we declare While to repeat adding Annotation
while num != 15 {
num += 1
//Add Annotation
let annotation = MKPointAnnotation()
annotation.coordinate = generateRandomCoordinates(70, max: 150) //this will be the maximum and minimum distance of the annotation from the current Location (Meters)
annotation.title = "Annotation Title"
annotation.subtitle = "SubTitle"
mapView.addAnnotation(annotation)
}
}
Generating Coordinates:
func generateRandomCoordinates(min: UInt32, max: UInt32)-> CLLocationCoordinate2D {
//Get the Current Location's longitude and latitude
let currentLong = currentLoc.coordinate.longitude
let currentLat = currentLoc.coordinate.latitude
//1 KiloMeter = 0.00900900900901° So, 1 Meter = 0.00900900900901 / 1000
let meterCord = 0.00900900900901 / 1000
//Generate random Meters between the maximum and minimum Meters
let randomMeters = UInt(arc4random_uniform(max) + min)
//then Generating Random numbers for different Methods
let randomPM = arc4random_uniform(6)
//Then we convert the distance in meters to coordinates by Multiplying the number of meters with 1 Meter Coordinate
let metersCordN = meterCord * Double(randomMeters)
//here we generate the last Coordinates
if randomPM == 0 {
return CLLocationCoordinate2D(latitude: currentLat + metersCordN, longitude: currentLong + metersCordN)
}else if randomPM == 1 {
return CLLocationCoordinate2D(latitude: currentLat - metersCordN, longitude: currentLong - metersCordN)
}else if randomPM == 2 {
return CLLocationCoordinate2D(latitude: currentLat + metersCordN, longitude: currentLong - metersCordN)
}else if randomPM == 3 {
return CLLocationCoordinate2D(latitude: currentLat - metersCordN, longitude: currentLong + metersCordN)
}else if randomPM == 4 {
return CLLocationCoordinate2D(latitude: currentLat, longitude: currentLong - metersCordN)
}else {
return CLLocationCoordinate2D(latitude: currentLat - metersCordN, longitude: currentLong)
}
}
Second: Adding Random Annotation on all of the earth
erdekhayser Code to get a Random Float number
func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}
And then Calling:
func generateAnnoLoc() {
var num = 0
//First we declare While to repeat adding Annotation
while num != 15 {
num += 1
//Add Annotation
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(randomBetweenNumbers(-90, secondNum: 90)), longitude: CLLocationDegrees(randomBetweenNumbers(-180, secondNum: 180)))
//-180 is the minimum of longitude and 180 is the maximum
//-90 is the minimum of latitude and 90 is the maximum
annotation.title = "Annotation Title"
annotation.subtitle = "SubTitle"
mapView.addAnnotation(annotation)
}
}
Third: Adding Random Annotation in Specific Country
You only want the Bounding box of the country or city You can find it Here
this Will Generate Random Coordinates in Egypt:
CLLocationCoordinate2D(latitude: CLLocationDegrees(randomBetweenNumbers(22, secondNum: 24.698099)), longitude: CLLocationDegrees(randomBetweenNumbers(31.674179, secondNum: 36.89468)))
You can use random double values between coordinate values in the earth for example:
do{
let latitude: CLLocationDegrees = randomLatitude()
let longitude: CLLocationDegrees = randomLongtitude()
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longtitude)
annotation = MKPointAnnotation()
annotation.coordinate = location
map.addAnnotation(annotation)
}while count == 15
P.S. Random value for swift you can look at this