MKMapItem Center for creating annotations - swift

I am trying to perform an MKLocalSearch.Request() and display the result on my mapView similar to this tutorial however when I do the search the coordinates returned are off center from where they should be. Where the map displays Brooklyn as an overlay in the center of the borough correctly the annotation is far off center to the left. I've noticed that there are two sets of coordinates contained in MKMapItem one the location and the other shown as center when printed to the console. I am not sure how to access the center coordinate but the center coordinate is the correct one in the middle of the screen. How can I access the center coordinate to use as the MKAnnotation's coordinate? Thank you
Search Code
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = "brooklyn"
searchRequest.region = MKCoordinateRegion(center: CLLocationCoordinate2DMake(40.758896, -73.985130), latitudinalMeters: 2000, longitudinalMeters: 2000)
let search = MKLocalSearch(request: searchRequest)
search.start { (response, error) in
if let error = error{
print("Error performing search for location")
}
if let response = response{
for item in response.mapItems{
print("map item returned: \(item)")
print("latitude: \(item.placemark.coordinate.latitude) longitude: \(item.placemark.coordinate.longitude)")
let annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
self.mapView.addAnnotation(annotation)
}
}
}
Output
map item returned: Optional(CLCircularRegion (identifier:'<+40.64529796,-73.94483550> radius 14090.15', center:<+40.64529796,-73.94483550>, radius:14090.15m))
latitude: 40.6924599 longitude: -73.9903805

I was able to access the center by casting the region property of MKMapItem's placemark property from CLRegion to CLCircularRegion.
if let response = response{
for item in response.mapItems{
print("map item returned: \(item.placemark)")
if let region = item.placemark.region as? CLCircularRegion{
print("region.center: \(region.center)")
let annotation = MKPointAnnotation()
annotation.coordinate = region.center
annotation.title = item.name
self.mapView.addAnnotation(annotation)
}
}

Related

GMUClusterRendererDelegate show marker iconview only when cluster is rendered and not before that swift 5

i am trying to create clusters in my google map. When i show clusters on map i want to show only the cluster count and when the cluster is clicked or zoom then only i want to show my Custom marker view.
Bu the marker view are already present before clustering and when i zoom in a cluster, the default pins are shown, which i dont want.
below is the code for clustering
for data in self.map_data {
//check if map data is on or off and show map data accordignly
let offerdata = data
let geocoder = CLGeocoder()
let strAddress = "\(offerdata.agent_street ?? "")"+" "+"\(offerdata.agent_city ?? "")"+" "+"\(offerdata.agent_zipcode ?? "")"
//MARK: GEOCODER FOR GETTING LAT LONG BASE ON ADDRESS
geocoder.geocodeAddressString(strAddress) {
placemarks, error in
let placemark = placemarks?.first
let lat = Double(placemark?.location?.coordinate.latitude ?? 0.00)
let lon = Double(placemark?.location?.coordinate.longitude ?? 0.00)
print("Lat: \(String(describing: lat)), Lon: \(String(describing: lon))")
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 5)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
marker.title = "\(offerdata.agent_firstname ?? "")"+" \(offerdata.agent_lastname ?? " ")"
marker.iconView?.backgroundColor = .lightGray
marker.userData = data
//amrut
// Clustering
let item = POIItem(position: CLLocationCoordinate2DMake(lat, lon), name: "marker.title" ?? "",data: data)
self.clusterManager.add(item)
//map info views
var image = UIImage()
var currency = String()
if data.currency == "AUD"{
currency = "$\(data.currency ?? "")"
}
else if data.currency == "EUR"{
currency = "€\(data.currency ?? "")"
}
else{
currency = "£\(data.currency ?? "")"
}
let amount = "\(data.offer_amount ?? "")".convertTo2Decimal+" "+currency
//create custom marker accordin to condtions
// "\(agent.offer_amount ?? "")".convertTo2Decimal+" "+"\(agent.currency ?? "AUD")"
if data.auto_approval_on_off == "ON"{
if (data.is_badge_display == "1") {
image = UIImage(named: "blueMarker.png") ?? UIImage()//blue
} else {
image = UIImage(named: "orangeMarker.png") ?? UIImage()//oranfge
}
}
else if (data.is_badge_display == "1") {
image = UIImage(named: "blueMarker.png") ?? UIImage()//blue
} else {
image = UIImage(named: "blackMarker.png") ?? UIImage()//black
}
let customMarker = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: 100, height: 40), image:image , lblText:amount)
// marker.iconView=customMarker
marker.map = self.MapView
self.MapView.camera = camera
}
}
and the same thing i do when in 'GMUClusterRendererDelegate willRenderMarker' delegate method and just uncomment the marker.iconView=customMarker
can anyone please help me what i need to be doing. It will be really helpful
Image for reference
Image for reference2
Two things i want:
1- show clustering for initial load without map icon views
2- show only map icon view and not the pins after cluster rendered/zoom
Please someone help me
I have a problem similar to this. The work around I came up with was to run the clearMarkers function and then re-add the entire array of markers back in using the addMarkers function
I'm still working on this so if I find a better answer I'll update

MapKit, Set current location manually ? It is possible?

How to display current location from coordinates manually? I am taking coordinates from another GPS device. How to set it manually?
Where the coordinates come from is largely immaterial: as long as you have one you can set the map to display an area including that point. If you want to display the point itself you can add an annotation:
A simple example method to drop a pin and zoom in to its location:
func createAnnotation(from coordinate: CLLocationCoordinate2D, title: String) -> MKPointAnnotation {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = title
return annotation
}
func dropPinAndZoomIn(to coordinate: CLLocationCoordinate2D){
var spanDelta = 0.035 //the width/height of the map area in degrees
let annotation = createAnnotation(from: coordinate, title: "My Location")
mapView.removeAnnotations(mapView.annotations) //clear any prev annotations
mapView.addAnnotation(annotation)
let span = MKCoordinateSpan(latitudeDelta: spanDelta, longitudeDelta: spanDelta)
let region = MKCoordinateRegion(center: coordinate, span: span)
let displayRegion = mapView.regionThatFits(region) //ensure the region can be displayed in the mapView's view
mapView.setRegion(displayRegion, animated: true)
}

Unable to remove previous polyline from last search

I have a slight problem, I am unable to remove the previous polyline created from the previous search.
I have looked at google documentation​ but i am unable to find the right answers.
let routes = json["routes"].arrayValue
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
print("routesOVER:",routeOverviewPolyline)
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSPath.init(fromEncodedPath: points!)
let polyline = GMSPolyline(path: path)
if polyline != nil {
print(polyline)
polyline.strokeColor = .black
polyline.strokeWidth = 10.0
polyline.map = self.googleMaps
}
}
}
catch let error as NSError {
print(error)
}
in the google maps, 2 polylines are shown. 1 from the previous search and another from the current search
Google Maps Image
You can clear the mapView before drawing to new polyline on the map.
self.googleMaps.clear()
But above code will clear pins on the map as well. your have to redraw your pins on the map as well

Showing multiple 'GMSMarker' markers on Google maps

I am trying to show multiple location using Google maps, the code showing only one location. I am using for loop. I checked the code using MKMapView and it's working.
Here is the code:
let dict = [self.jsonElement]
for dicts in dict {
let latiCon = (dicts.value(forKey: "lati") as! NSString).doubleValue
let longiCon = (dicts.value(forKey: "longi") as! NSString).doubleValue
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.
let camera = GMSCameraPosition.camera(withLatitude: latiCon, longitude: longiCon, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latiCon, longitude: longiCon)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
I need to show multiple locations as I said, I have a look to relative answers but I did not find anything match with my question.
this code
let camera = GMSCameraPosition.camera(withLatitude: latiCon, longitude: longiCon, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
makeing a new mapView every time in loop so it's natural what you get.
a new mapview + one marker .
move this code outside loop or delete it if you already have a mapview declared before.

How to open a info windows by default using swift [duplicate]

I am new to iOS development. This is regarding Marker info window in Google Maps iOS SDK.
I understand, we can create a marker with info window using GMSMarkerOption.
GMSMarkerOption *myLocationOption = [GMSMarkerOption alloc];
myLocationOption .title = #"My Location";
myLocationOption .snippet = #"Lat:...., Lang:....";
[mapView addMarkerOption:myLocationOption];
As per the above code, Marker displayed in the Map View as expected.
And tapping on marker shows the "My Location" info window in Google maps which is good.
Is there anyway we can show the info window programmatically when the user goes to Custom Map Screen?
This has changed on Google Maps SDK and it's easier to understand:
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = coordinate;
marker.title = #"Location selected";
marker.snippet = #"Testing";
marker.map = mapView_;
//Show info window on map
[mapView_ setSelectedMarker:marker];
You use now setSelectedMarker method to show an info window of a marker
GMSMarkerOptions *myLocationOptions = [GMSMarkerOptions options];
myLocationOptions.title = #"My Location";
myLocationOptions.snippet = #"Lat:...., Lang:....";
mapView.selectedMarker = [mapView addMarkerWithOptions:myLocationOptions];
(note that it's Options, not Option)
Swift 3.0
func addMarker(_ location:CLLocation){
var locationMarker: GMSMarker!
if locationMarker != nil {
locationMarker.map = nil
}
locationMarker = GMSMarker(position: location.coordinate)
locationMarker.map = mapView
locationMarker.appearAnimation = kGMSMarkerAnimationPop
locationMarker.icon = GMSMarker.markerImage(with: UIColor.green)
locationMarker.opacity = 0.85
locationMarker.isFlat = true
locationMarker.snippet = "My Location"
mapView.selectedMarker=locationMarker
}
below line is the answer
mapView.selectedMarker=locationMarker
swift 3
self.mapView.selectedMarker = marker
In the case of swift 3, you can open the snipet usint the selectedMarker
If you are creating the marker in a similar way to:
marker.position = CLLocationCoordinate2D(latitude: 34.1331168, longitude: -118.3550723)
marker.title = "My super place name"
marker.snippet = "Are you looking a place to play? This is your place! "
marker.appearAnimation = kGMSMarkerAnimationPop
marker.map = self.mapView
// Below line will shows the infowindow for marker with out tapping on it
[mapView setSelectedMarker:myLocationOptions]; // myLocationOptions is your desired GMSMarker to show Infowindow with out tapping .
Happy Coding :)
mMapView.selectedMarker = marker
GMSMarkerOptions is deprecated. Using this helped me to show info window without tapping-
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
myMapView.selectedMarker = myGMSMarker
}
--> It shows multiple infoWindows without tapping on marker. You can easily customise it.
for i in 0..
let dict = arrNearByPlacesArray.object(at: i) as? NSDictionary ?? [:]
let lat = dict.object(forKey: "latitude") as? String ?? ""
let long = dict.object(forKey: "longitude") as? String ?? ""
let company_id = dict.object(forKey: "company_id") as? String ?? ""
let totaljobs = dict.object(forKey: "totaljobs") as? String ?? ""
let location = CLLocationCoordinate2D(latitude: Double(lat) ?? 0.0, longitude: Double(long) ?? 0.0)
print("location: \(location)")
let marker = GMSMarker()
//marker.icon = UIImage(named: "maps")
let viewData = Bundle.main.loadNibNamed("MarkerXibView", owner: self, options: nil)?.first as! MarkerXibView . //UIView
marker.iconView = viewData . //UIView
marker.position = location
marker.accessibilityLabel = company_id
marker.map = vwGoogleMap
}