Get all GMSMarker from mapview and remove all marker without using mapview.clear()
I have drawn path with marker in google map. So the path is static but marker needs to change their positions. How can I remove all markers without using mapview.clear()
, because it will clear my path also from the map.
Any solution?
1 answer
-
answered 2017-10-11 10:14
Nikhil Manapure
I guess you will have to keep all markers in an array(eg.
allMarkers
). Then,for marker in allMarkers { marker.map = nil }
See also questions close to this topic
-
How to draw a overlay view on top of Navigation and tab bar
I want to show a over lay view on top of the exisitng navigationbar and tabbaritems int he bottom.
I tried adding the overlay view's view on application window directly but wouldn't work any idea.
Here is my custom view with all constraints
-(void)showView{ animationOverlay=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 400, 400)]; animationOverlay.translatesAutoresizingMaskIntoConstraints=false; UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; [btn setFrame:CGRectMake(0, 0, 100, 100)]; [btn setTitle:@"Go" forState:UIControlStateNormal]; [btn setTranslatesAutoresizingMaskIntoConstraints:false]; [animationOverlay setBackgroundColor:[UIColor redColor]]; NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:animationOverlay attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute: NSLayoutAttributeLeft multiplier:1.0 constant:0]; NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:animationOverlay attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute: NSLayoutAttributeWidth multiplier:1.0 constant:0]; NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:animationOverlay attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute: NSLayoutAttributeTop multiplier:1.0 constant:0]; NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:animationOverlay attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute: NSLayoutAttributeBottom multiplier:1.0 constant:0]; NSLayoutConstraint *centreXConstraint= [NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:animationOverlay attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]; NSLayoutConstraint *centreYConstraint= [NSLayoutConstraint constraintWithItem:btn attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:animationOverlay attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; [self.view addSubview:animationOverlay]; [self.view addConstraint:leftConstraint]; [self.view addConstraint:rightConstraint]; [self.view addConstraint:topConstraint]; [self.view addConstraint:bottomConstraint]; [animationOverlay addSubview:btn]; [self.view addConstraint:centreXConstraint]; [self.view addConstraint:centreYConstraint]; } -(void)hideView{ [animationOverlay removeFromSuperview]; }
right now I can do this inside a viewcontroller's view succesfully
ANy ideas on how to do this..
I couldn't think a way how to do this without breaking the constraints
any ideas,suggestions are welcome
-
Delegates with Swift
Currently I have a ViewController with a TableView and a custom Header containing a back button. What I want is to say from the header class that the ViewController has to go back to the previous ViewController. The problem I'm facing is that I'm conforming the protocol and the action of the button is received but the debugger doesn't go to the dismiss function. Here's the code:
protocol StoresFilterHeaderViewDelegate: class { func onBackButtonTap(); } class StoresFilterHeaderView: UICollectionReusableView { weak var delegate: StoresFilterHeaderViewDelegate?; @IBOutlet weak var lbSubcategory: UILabel! @IBOutlet weak var ivSubcategory: UIImageView! // MARK: Actions @IBAction func onBackToMomentDetailButtonTap(_ sender: AnyObject) { self.delegate?.onBackButtonTap(); print("button pressed"); } }
"button pressed" is printed well
class StoresFilterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, StoresFilterHeaderViewDelegate { func onBackButtonTap() { print("segueback") }
"segueback" is not being printed
-
Unreal Engine / IOS - Associated Domains / Universal links
Was wondering how to set up IOS Universal Links / Associated Domains in Unreal Engine.
Basically we have two apps, one an older app built in IOS native/Xcode and a new side app showing off some new features/marketing that was built in Unreal Engine 4.18 (BluePrints only). The goal is to have them be able to deep link to eachother and make use of Universal Links overall for marketing/usage purposes. This isn't a problem with the older IOS native app as XCode can handle this but there seems to be no documentation on how to make sure the entitlements are setup correctly in Unreal Engine for this.
I'm probably missing something very simple (like the naming structure of the Bundle Identifier) but curious on what to do in that regard.
-
HTML entities in strings files
I wan't to customize the font of my strings for exemple I have 2 languages:
"Hello how are you $name ?"
"Bonjour comment vas tu $prenom ?"
Here for exemple I wan't to make :
- "Hello" and "Bonjour" in bold;
- "how" and "comment" in a custom font;
- "are you" and "vas tu" in red;
- and have a parameter to get name.
It is possible to do it in swift? I have created one of the file:
I tried to put HTML entities:
How I call it:
let gotham = [ NSAttributedStringKey.font: UIFont(name: "gotham-book", size: 18.0)! ] let gothamBold = [ NSAttributedStringKey.font: UIFont(name: "gotham-bold", size: 18.0)! ] let gothamOrange = [NSAttributedStringKey.foregroundColor: UIColor.orange, NSAttributedStringKey.font: UIFont(name: "gotham-book", size: 18.0)!] let accueilTopTextL1 = NSMutableAttributedString(string: NSLocalizedString("accueilTopTextL1", comment: ""), attributes: gotham) let accueilTopTextL2 = NSMutableAttributedString(string: NSLocalizedString("accueilTopTextL2", comment: ""), attributes: gothamBold) let accueilTopTextL3 = NSMutableAttributedString(string: NSLocalizedString("accueilTopTextL3", comment: ""), attributes: gotham)
-
Cannot get correct audio files to play from array
When I tap on any of my cells in my table view they all play the same song in the first array. How do I make them play the song that is assigned to their individual array? The func automaticPlay() is responsible for dealing with the audio on this vc. When the cell is tapped the song should play automatically.
import UIKit import Firebase import FirebaseAuth import FirebaseDatabase import FirebaseStorage import AVFoundation class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableViewProducts: UITableView! var delegate: ListViewController? var ref:DatabaseReference? var databaseHandle: DatabaseHandle? let audioStuffed = false let audioPlayer = AVPlayer() var postData = [productsList]() var player: AVPlayer! func automaticPlay() { let indexPath = IndexPath(row: 0, section: 0) let audioUp = postData[indexPath.row].audio let url = audioUp player = AVPlayer(url: URL(string: url!)!) player.volume = 1.0 player.rate = 1.0 if player.rate == 0 { player.play() print("It's Playing") } } override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference().child("AudioDB") loadProducts() do { try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return postData.count } func loadProducts() { ref?.observe(DataEventType.value, with: { (snapshot) in var newSweets = [productsList]() for post in snapshot.children { let postObject = productsList(snapshot: post as! DataSnapshot) newSweets.append(postObject) print(self.postData) } self.postData = newSweets self.tableViewProducts.reloadData() }) { (error:Error) in print(error) } } //This places the text on the ViewControllerTableViewCell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell let sweet = postData[indexPath.row] cell.idLbl.text = sweet.id cell.nameLbl.text = sweet.p_name if let profileImageUrl = sweet.image{ let url = URL(string: profileImageUrl) URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in if error != nil { print(error) return } DispatchQueue.main.async { cell.productImage.image = UIImage(data: data!) } }).resume() } return cell } var selectedRowIndex = -1 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == selectedRowIndex { automaticPlay() return 200 //Expanded } return 40//Not expanded } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if selectedRowIndex == indexPath.row { selectedRowIndex = -1 } else { selectedRowIndex = indexPath.row } tableView.reloadRows(at: [indexPath], with: .automatic) } }
-
Why do layer shadows not work within a UIScrollView?
My intention: I'd like to draw a shadow around a view. This sounds simple, so I made my own subclass of
UIView
as following:@IBDesignable class RoundedView: UIView { @IBInspectable var cornerRadius : CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var borderWidth : CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor : UIColor? { didSet { layer.shadowOpacity = 1 layer.shadowRadius = 0 layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowColor = UIColor.gray.cgColor layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath } } }
Just to test this out, I set the shadowRadius etc. to a constant value.
This works as intended when dragging a
UIView
onto aUIViewController's
main view in Xcode InterfaceBuilder; however, it does not seem to work with the following structure (see the screenshot):where the
RoundedView
is my custom view from above, theGradient View
is just a normalUIView
(color gradient).When running the app in the simulator, I get the following output:
As you can see, the shadow goes way too far to the right. I also checked both the shadowPath and the bounds of the view, they're equal.
The shadowPath, bounds and frame:
Path 0x608000236b00: moveto (0, 0) lineto (300, 0) lineto (300, 52) lineto (0, 52) closepath (0.0, 0.0, 300.0, 52.0) (37.0, 397.5, 300.0, 52.0)
It's strange that this only appears within the
UIScrollView
.In addition, if I click on "Debug View Hierarchy", it is drawn correctly in Xcode.
Can someone reproduce this?
Thanks for help.
-
Get near by cities using google maps api
I want to get a near by cities with a given city I have, for example near by cities of New York. I suppose to get all cities that near by New York with its name , lng and lat
-
Scale custom marker on map based on zoom level
I'm drawing a simple circle on my map by doing the following:
@Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; try { boolean success = mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.style_json)); if (!success) { Log.e("MapsActivityRaw", "Style parsing failed."); } } catch (Resources.NotFoundException e) { Log.e("MapsActivityRaw", "Can't find style.", e); } final LatLng myLatlng = new LatLng(-33.999564, 18.516763); mMap.moveCamera(CameraUpdateFactory.newLatLng(myLatlng)); mMap.animateCamera( CameraUpdateFactory.zoomTo( 11.0f ) ); mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { public void onMapLoaded() { bar.setVisibility(View.GONE); drawCircle(myLatlng); } }); } private void drawCircle(LatLng point){ CircleOptions circleOptions = new CircleOptions(); circleOptions.center(point); circleOptions.radius(500); circleOptions.strokeColor(Color.BLACK); circleOptions.fillColor(0x30ff0000); circleOptions.strokeWidth(2); mMap.addCircle(circleOptions); }
This works perfectly, a circle is drawn to the map as expected.
The problem is that when I zoom in and out the size of the circle increases/decreases.
My Question:
I'm looking for a way to keep the size of the circle the same when zooming in and out.
Also..
I don't want to use marker clustering.
-
change gesturehandling in embedded google maps in iframe, no api, no js
I want to change the gesture handling from cooperative to greedy, in the iframe of an embedded goole maps. Im using Wordpress and do not know how to use javascript or php. So i just want to feed the iframe-code with the order something like: function="gesture handling:greedy" - but function did not work.
Found nothing in goole, am I the only one who does not like the new scroll thing?
Thanks!
-
Google maps iOS, Marker, Marker Position
In GoogleMaps(iOS) markers selected marker not comes front all the markers are one behind another. If markers are at same location unable to differentiate which market got selected.
If anyone knows please provide solution.
-
Where to find the list of markers available using the Google Maps API
In the documentation section for Google Maps API, this page describes how put one of googles markers in your map. It seems the icon's url is https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png which lead me to look higher up in that hierarchy for other markers. I am, however, only getting 404s when I do and can't seem to find any answers online as to where I can find what other markers are available.
How can I browse the API's available markers?
-
Dynamically adding marker to Google Maps [Android]
I have an issue when trying to add a marker dynamically to my google maps. The error I get is:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mView = inflater.inflate(R.layout.fragment_map, container, false); mapView = (MapView) mView.findViewById(R.id.map); if (mapView != null) { mapView.onCreate(null); mapView.onResume(); mapView.getMapAsync(this); } return mView; } @Override public void onMapReady(GoogleMap googleMap) { MapsInitializer.initialize(getContext()); this.map = googleMap; googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); } public void populatePositions(final String jsonString) { Thread t = new Thread(new Runnable() { public void run() { try { JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("location"); JSONObject object; for (int i = 0; i < jsonArray.length(); i++) { object = jsonArray.getJSONObject(i); String member = object.getString("member").toString(); String longitude = object.getString("longitude").toString(); String latitude = object.getString("latitude").toString(); addMarker(member, Double.parseDouble(latitude), Double.parseDouble(longitude)); } } catch (JSONException e) { e.printStackTrace(); } } }); t.start(); } public void addMarker(String name, double latitude, double longitude){ map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(name)); }
This is the code I have. The map is initialized in OnMapReady, but when the server sends a location to add, It crashes due to map not being initialized.
-
SWIFT add GMSMarker to GMSMapView from a UICollectionViewCell
Using the Google Map SDK, I am trying to add markers to a map as a user scrolls through a uicollectionview that is inside a tableview, inside a view controller (see image). Everything works great, and the function below loads markers to the map when called from MapViewConroller. The problem is that calling the function from the Collection View Cell results in no markers being added. Does this have something to do with how I am accessing mapView?
func loadMarker(atIndex:Int){ print("loadMarker Initiated") //search the geojson for the object with id = atIndex // and get the properties and geometry let object = features.filter({return $0["id"] as! String == atIndex}) let properties = (object[0]["properties"] as? [String: Any])! let geometry = (object[0]["geometry"] as? [String: Any])! //prepare marker properties/position let marker_id = properties["globalid"] let coordinates = geometry["coordinates"] as! NSArray let lng = coordinates[0] as! CLLocationDegrees let lat = coordinates[1] as! CLLocationDegrees let position = CLLocationCoordinate2D(latitude: lat, longitude: lng) var selectedMarkerType = UIImage(named: "stairIcon.png") //Create New Marker and apply properties let NewMarker = GMSMarker(position: position) NewMarker.title = (marker_id! as! String) NewMarker.icon = selectedMarkerType! //Add the marker to the map on the main thread DispatchQueue.main.async{ NewMarker.map = self.mapView } }
CollectionView Cell:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let mapViewController = MapViewController() var reuseIdentifier = "InfoWindowCollectionViewCell" guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? InfoWindowCollectionViewCell else { fatalError("error") } var visibleIndex = 0 if indexPath.row > 0 { visibleIndex = indexPath.row-1 } var Title = globalVisibleMarker[indexPath.row].title cell.infoWindowCollectionViewLabel.text = Title mapViewController.loadMarker(atIndex: visibleIndex) }
Thank you
-
Creating a zone following a route using Google map iOS SDK
For my current map based application, I need to have the following features on Google Map iOS SDK
- User will select a source and a destination.
- User will put a few turning points on the map to reach from source to destination.
- User will also provide a width in meter.
- Now using this turning points and width I need to create a zone as specified in the following hand made sketch.
I tried to create a polygon using GMSMutablePath. User was also able to drag each marker and resize and reposition the zone.
I have also tried to understand Create a hollow polygon but could not find out a way to generate encoded string to use in the following example code.
let hydePark = "tpwmEkd|y[QVe@Pk@BsHe@mGc@iNaAKMaBIYIq@qAMo@Eo@@[Fe@DoALu@HUb@c@XUZS^ELGxOhAd@@ZB`@J^BhFRlBN\\BZ@`AFrATAJAR?rAE\\C~BIpD" let archibaldFountain = "tlvmEqq|y[NNCXSJQOB[TI" let reflectionPool = "bewmEwk|y[Dm@zAPEj@{AO" let polygon = GMSPolygon() polygon.path = GMSPath(fromEncodedPath: hydePark) polygon.holes = [GMSPath(fromEncodedPath: archibaldFountain)!, GMSPath(fromEncodedPath: reflectionPool)!]
In my exploration project, user was specifying the location coordinate, which I do not want. Rather user will just put the turning points on the maps and provide the width and the zone will be calculated automatically.
If there is any existing functionality from GoogleMaps SDK to achieve that? Or I need to follow a complex geometric calculation to draw the zone?
-
Convert GMSMapView coordinate to iPhone screen point(x,y)
I have tried to covert the marker position latitude-longitude to iPhone screen x and y coordinate, but it gives me negative value sometimes.
MapView is added in main view from storyboard. self.mapView.frame - It is equal to main view frame iPhone 8 plus simulator = (origin = (x = 0, y = 0), size = (width = 414, height = 736))
Marker position : (latitude = 22.811061859130859, longitude = 70.862533569335938)
CGPoint pointInScreen = [self.mapView.projection pointForCoordinate:marker.position];
Returns value - (x = -38547.58203125, y = 7061.60107421875) Which is not screen point. My marker is visible on the screen.
Can anyone suggest me the right way to find out the screen x,y coordinate based on the marker latitude-longitude position?