I am trying to dynamically set the pin color for these two points which belong to different classes however they do not show a different color on my map. Do you see any issue in my for loop for my array, towards the bottom?
#define UNIVERSITY_LATITUDE 35.22836;
#define UNIVERSITY_LONGITUDE 126.84784;
#define HOTEL_LATITUDE 34.55;
#define HOTEL_LONGITUDE 127.36;
#implementation MapKitViewController
//Synthesize the getters and setters of the map view
#synthesize mapView;
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *annotations = [[NSMutableArray alloc] init];
CLLocationCoordinate2D location;
//used to test Annotations of map, will be replaced by for loop to insert new points
PhotoPoint *photoAnn;
photoAnn = [[PhotoPoint alloc] init];
location.latitude =UNIVERSITY_LATITUDE;
location.longitude = UNIVERSITY_LONGITUDE;
photoAnn.coordinate = location;
[photoAnn setTitle:#"GIST"];
[photoAnn setSubtitle:#"University"];
[photoAnn setAnnotationType:#"Photo"];
[annotations addObject:photoAnn];
CommercialPoint *commAnn;
commAnn = [[CommercialPoint alloc] init];
location.latitude =HOTEL_LATITUDE;
location.longitude = HOTEL_LONGITUDE;
commAnn.coordinate = location;
[commAnn setTitle:#"Hotel"];
[commAnn setSubtitle:#"Hotel Center"];
[commAnn setAnnotationType:#"Commercial"];
[annotations addObject:commAnn];
for (id eachObject in annotations){
if ([eachObject isKindOfClass:[PhotoPoint class]])
{
photoAnn.pinColor = MKPinAnnotationColorGreen;
}
if ([eachObject isKindOfClass:[CommercialPoint class]])
{
commAnn.pinColor = MKPinAnnotationColorPurple;
}
//send the delgate messages to the mapview
mapView.delegate = self;
[self.mapView addAnnotations:annotations];
Related
I want to show multiple marker on google map. There are answers based on this. But markers are not showing on the map. Although I am getting the latitude and longitude value based on the array result. What should I do?
Note: I have done some changes and the code running perfectly.
My code is:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self performRequestForRestaurantListing];
geometryDict=[[NSMutableDictionary alloc]init];
locationDict=[[NSMutableDictionary alloc]init];
NSLog(#"the value of list is %#", _service);
NSLog(#"the value of stringradius is %#", _stringRadius);
/*---location Manager Initialize-------*/
self.manager=[[CLLocationManager alloc]init];
self.manager.distanceFilter = 100;
self.manager.desiredAccuracy = kCLLocationAccuracyBest;
[self.manager requestAlwaysAuthorization];
self.manager.delegate=self;
[self.manager startUpdatingLocation];
[mapView setDelegate:self];
latitude=#"22.5726";
longitude=#"88.3639";
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude doubleValue]
longitude:[longitude doubleValue]
zoom:12];
[mapView animateToCameraPosition:camera];
[self coordinateOnMap:latitude andWithLongitude:longitude];
}
-(void)coordinateOnMap:(NSString*)latitude andWithLongitude:(NSString*)longitude
{
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] init];
CLLocationCoordinate2D location;
for (int i=0;i<[restaurantList count];i++)
{
driverMarker = [[GMSMarker alloc] init];
latitude=[[[[restaurantList objectAtIndex:i]objectForKey:#"geometry"]objectForKey:#"location"] objectForKey:#"lat"];
longitude=[[[[restaurantList objectAtIndex:i]objectForKey:#"geometry"]objectForKey:#"location"] objectForKey:#"lng"];
location.latitude = [latitude floatValue];
location.longitude = [longitude floatValue];
driverMarker.position = CLLocationCoordinate2DMake(location.latitude, location.longitude);
driverMarker.map = mapView;
}
driverMarker.icon=[UIImage imageNamed:#"marker"];
bounds = [bounds includingCoordinate:driverMarker.position];
driverMarker.title = #"My locations";
[driverMarker setTappable:NO];
mapView.myLocationEnabled = YES;
}
I guess your driveMarker gets deallocated by ARC immediatly after each loop.
If this really is your issue, you'll have to make sure that those markers "survive" the loop, e.g. with the following code:
#implementation MyController
#property (nonatomic) NSMutableArray *allMarkers;
- (void)viewDidLoad {
allMarkers = [[NSMutableArray alloc] init];
// ...
}
-(void)coordinateOnMap:(NSString*)latitude andWithLongitude:(NSString*)longitude {
//...
[allMarkers removeAllObjects];
for (int i=0;i<[restaurantList count];i++) {
GMSMarker *driverMarker = [[GMSMarker alloc] init];
[allMarkers addObject:driveMarker];
// ...
}
}
#end
This will create an NSArray property to store all created markers, just to keep them in scope.
I am trying to annotate some locations in map using MapBox. and its done.
But the problem is some other annotations are seen in map without any reference, i.e we cant click on it and when i zoom in/zoom out it disappears.
Am only try to create two annotations including user location.
How this happen?
is it because any reusing of annotation?
Some code snippets used:
1) creating annotation in loop
MGLPointAnnotation *point = [[MGLPointAnnotation alloc] init];
point.coordinate = coordinate;
point.title = location;
NSString *altString =[NSString stringWithFormat:#"%#",mIsNSDictionary(response)?[response objectForKey:kKeyAlt]:response];
NSString *str = [NSString stringWithFormat:kKeyLocationLatLonNAltInBaidu,coordinate.latitude,coordinate.longitude,[altString floatValue]];
point.subtitle = str;
[self.arrayAnnotations addObject:point];
[self.mapView addAnnotation:point];
Note: self.arrayAnnotations contains only 2 points
2) Delegate method for annotation
-(MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
if([annotation isKindOfClass:[MGLPointAnnotation class]] && [self.arrayAnnotations containsObject:annotation]) {
NSString *reuseIdentifier = [self makeIdentifierString:annotation];
MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:reuseIdentifier];
if (!annotationImage) {
annotationImage = [MGLAnnotationImage annotationImageWithImage:[UIImage imageNamed:kImageNameMarker] reuseIdentifier:reuseIdentifier];
}
return annotationImage;
}
return nil;
}
Is there any way to change default marker icon in marker clustering?
Here is my code...
- (void)viewDidLoad {
[super viewDidLoad];
// Set up the cluster manager with a supplied icon generator and renderer.
id<GMUClusterAlgorithm> algorithm = [[GMUNonHierarchicalDistanceBasedAlgorithm alloc] init];
id<GMUClusterIconGenerator> iconGenerator = [[GMUDefaultClusterIconGenerator alloc] init];
id<GMUClusterRenderer> renderer = [[GMUDefaultClusterRenderer alloc] initWithMapView:googleMapView
clusterIconGenerator:iconGenerator];
clusterManager = [[GMUClusterManager alloc] initWithMap:googleMapView
algorithm:algorithm
renderer:renderer];
// Register self to listen to both GMUClusterManagerDelegate and
// GMSMapViewDelegate events.
[clusterManager setDelegate:self mapDelegate:self];
}
- (void)loadView {
// Create a GMSCameraPosition that tells the map to display the
_camera = [GMSCameraPosition cameraWithLatitude:29.3117
longitude:47.4818
zoom:8];
googleMapView = [GMSMapView mapWithFrame:CGRectZero camera:_camera];
googleMapView.myLocationEnabled = YES;
googleMapView.settings.compassButton = YES;
googleMapView.settings.myLocationButton = YES;
googleMapView.delegate = self;
self.view = googleMapView;
}
-(void)setLocation:(CLLocation *)location
{
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
[googleMapView animateToLocation:center];
[googleMapView animateToZoom:12];
NSMutableArray *array = [NSMutableArray arrayWithObjects:
#"29.0827,48.1363",
#"29.2679,47.9927",
#"29.348706, 48.092425",
#"29.340925, 48.088477",
#"29.324912, 48.089850",
#"29.330599, 47.990630",
#"29.300364, 47.960589",
#"29.271917, 47.918017",
#"29.3032,47.936", nil];
//remove all clusters before adding clusters
[clusterManager clearItems];
for (int i = 0; i < [array count]; i++)
{
center = CLLocationCoordinate2DMake ([[array[i] componentsSeparatedByString:#","][0] floatValue], [[array[i] componentsSeparatedByString:#","][1] floatValue]);
// Add items to the cluster manager.
NSString *name = nil;//[NSString stringWithFormat:#"Item %d", i];
id<GMUClusterItem> item =[[POIItem alloc] initWithPosition:center
name:name];
[clusterManager addItem:item];
}
// Call cluster() after items have been added
// to perform the clustering and rendering on map.
[clusterManager cluster];
}
Please guide me...
I see that you used google-maps-ios-utils. The problem is that there is no API for change marker's icon yet. You can only do it directly in the code of the library. I've pasted my custom code inside the method
- (GMSMarker *)markerWithPosition:(CLLocationCoordinate2D)position
from:(CLLocationCoordinate2D)from
userData:(id)userData
clusterIcon:(UIImage *)clusterIcon
animated:(BOOL)animated{
//...
if (clusterIcon != nil) {
marker.icon = clusterIcon;
marker.groundAnchor = CGPointMake(0.5, 0.5);
} else {
if([[marker.userData class] isSubclassOfClass:[POIItem class]]){
POIItem *item = (POIItem *)marker.userData;
MarkerIcon* markerView = (MarkerIcon *)[[NSBundle mainBundle] loadNibNamed:#"MarkerIcon" owner:marker options:nil][0];
marker.iconView = markerView;
marker.groundAnchor = CGPointMake(0.5, 0.5);
}
}
}
It is not a good way to change the code like this. But I could not find better solution for that moment.
I have already sovled this question.
I used googleMaps Api version:8.1.
Here is my code...
#import "Clustering/GMUClusterItem.h"
// Point of Interest Item which implements the GMUClusterItem protocol.
#interface POIItem : NSObject<GMUClusterItem>
#property(nonatomic, readonly) CLLocationCoordinate2D position;
#property(nonatomic, readonly) NSString *name;
- (instancetype)initWithPosition:(CLLocationCoordinate2D)position name:(NSString *)name;
#end
1.creat the map.
#interface BasicViewController ()<GMUClusterManagerDelegate, GMSMapViewDelegate,
GMUClusterRendererDelegate>
#end
typedef NS_ENUM(NSInteger, ClusterAlgorithmMode) {
kClusterAlgorithmGridBased,
kClusterAlgorithmQuadTreeBased,
};
#implementation BasicViewController {
GMSMapView *_mapView;
GMUClusterManager *_clusterManager;
}
- (void)loadView {
//创建地图
GMSCameraPosition *camera =
[GMSCameraPosition cameraWithLatitude:kCameraLatitude longitude:kCameraLongitude zoom:10];
_mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = _mapView;
}
2.creat GMUClusterManager object.
- (void)viewDidLoad {
[super viewDidLoad];
//添加标注算法方式
id<GMUClusterAlgorithm> algorithm = [self algorithmForMode:kClusterAlgorithmQuadTreeBased];
//标注icon
id<GMUClusterIconGenerator> iconGenerator = [self iconGeneratorWithImages];//[self defaultIconGenerator];
// CustomClusterIconGenerator *iconGenerator = [[CustomClusterIconGenerator alloc] init];
GMUDefaultClusterRenderer *renderer =
[[GMUDefaultClusterRenderer alloc] initWithMapView:_mapView
clusterIconGenerator:iconGenerator];
renderer.delegate = self;
_clusterManager =
[[GMUClusterManager alloc] initWithMap:_mapView algorithm:algorithm renderer:renderer];
// Generate and add random items to the cluster manager.
//将标注添加到地图上
[self generateClusterItems];
// Call cluster() after items have been added to perform the clustering and rendering on map.
//展示
[_clusterManager cluster];
// Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
[_clusterManager setDelegate:self mapDelegate:self];
UIBarButtonItem *removeButton =
[[UIBarButtonItem alloc] initWithTitle:#"Remove"
style:UIBarButtonItemStylePlain
target:self
action:#selector(removeClusterManager)];
self.navigationItem.rightBarButtonItems = #[ removeButton ];
}
3.in method :
/*You can set marker image here
if [marker class] is POIItem.
*/
- (void)renderer:(id<GMUClusterRenderer>)renderer willRenderMarker:(GMSMarker *)marker {
if ([marker.userData isKindOfClass:[POIItem class]]) {
POIItem *item = marker.userData;
marker.title = item.name;
******marker.icon = [UIImage imageNamed:#"register"];******
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making this app where people can see what tourist attractions are near them and I'm a bit stuck!
I need it to load the user's current location when the app is loaded and zoom to it, however it's not doing so.
Sorry to be a bit blunt but I really don't know how to set it up so that it will work with both the button and load their location automatically.
https://pbs.twimg.com/media/BcRSTk0CAAEV47Q.jpg
ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController{
MKMapView *mapview;
}
#property (weak, nonatomic) IBOutlet MKMapView *myMapView;
-(IBAction)getlocation;
#end
ViewController.m
#import "ViewController.h"
#import "Annotation.h"
#interface ViewController ()
#end
//Thorpe Park Coordinates
#define THORPE_LATITUDE 51.40395;
#define THORPE_LONGITUDE -0.51433;
//London Eye Coordinates
#define LONDONEYE_LATITUDE 51.50340;
#define LONDONEYE_LONGITUDE -0.11952;
//The New London Dungeons
#define LONDONDUGNEONS_LATITUDE 51.50231;
#define LONDONDUGNEONS_LONGITUDE -0.11965;
//Span
#define THE_SPAN 0.50f;
#implementation ViewController
#synthesize myMapView;
-(IBAction)getlocation {
mapview.showsUserLocation = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Create Region
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude = LONDONEYE_LATITUDE;
center.longitude = LONDONEYE_LONGITUDE;
//Span
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span = span;
//Set our mapView
[myMapView setRegion:myRegion animated:YES];
//Annotation's
NSMutableArray * locations = [ [NSMutableArray alloc] init];
CLLocationCoordinate2D location;
Annotation *myAnn;
//London Eye
myAnn = [[Annotation alloc] init];
location.latitude = LONDONEYE_LATITUDE;
location.longitude = LONDONEYE_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"The London Eye";
myAnn.subtitle = #"";
[locations addObject:myAnn];
//The New London Dungeons
myAnn = [[Annotation alloc] init];
location.latitude = LONDONDUGNEONS_LATITUDE;
location.longitude = LONDONDUGNEONS_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"The London Dungeons";
myAnn.subtitle = #"";
[locations addObject:myAnn];
//Thorpe Park
myAnn = [[Annotation alloc] init];
location.latitude = THORPE_LATITUDE;
location.longitude = THORPE_LONGITUDE;
myAnn.coordinate = location;
myAnn.title = #"Thorpe Park";
myAnn.subtitle = #"";
[locations addObject:myAnn];
[self.myMapView addAnnotations:locations];
/*
//1. Create a coordinate to be used with pin
CLLocationCoordinate2D ThorpeLocation;
ThorpeLocation.latitude = THORPE_LATITUDE;
ThorpeLocation.longitude = THORPE_LONGITUDE;
Annotation * myAnnotation = [Annotation alloc];
myAnnotation.coordinate = ThorpeLocation;
myAnnotation.title = #"Thorpe Park";
myAnnotation.subtitle = #"Theme Park";
[self.myMapView addAnnotation:myAnnotation];
*/
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Use this, and don't forget to put the delegate on your .h file, hope it works ;)
_mapView.userTrackingMode = YES;
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.00001;
span.longitudeDelta = 0.00001;
CLLocationCoordinate2D location = _mapView.userLocation.coordinate;
region.span = span;
region.center = location;
[_mapView setRegion:region animated:TRUE];
[_mapView regionThatFits:region];
}
G'day All,
I am trying to change the colours of the pins in MKPointAnnotations. Most of the code examples I have tried to follow are too complex for me to follow. I have come up with this:
//
// ViewController.m
// PlayingWithMaps
//
// Created by custom on 22/09/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotationPoint
{
static NSString *annotationIdentifier = #"annotationIdentifier";
MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotationPoint reuseIdentifier:annotationIdentifier];
pinView.pinColor = MKPinAnnotationColorPurple;
return pinView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// First, choose what type of map
//mapView.mapType = MKMapTypeHybrid;
mapView.mapType = MKMapTypeStandard;
// Second, where is the centre of the map
CLLocationCoordinate2D centreCoord = {.latitude = -37.123456, .longitude = 145.123456};
MKCoordinateSpan mapSpan = {.latitudeDelta = 0.001, .longitudeDelta = 0.001};
MKCoordinateRegion region = {centreCoord, mapSpan};
[mapView setRegion:region];
// Now lets make a single annotation.
CLLocationCoordinate2D annotationCoordinate;
annotationCoordinate.latitude = -37.781650;
annotationCoordinate.longitude = 145.076116;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc]init];
annotationPoint.coordinate = annotationCoordinate;
annotationPoint.title = #"My point of interest";
annotationPoint.subtitle = #"Location";
[mapView addAnnotation:annotationPoint];
// Read a set of points from files into arrays
NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"latitudes" ofType:#"txt"] encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *latitudeStringsArray = [NSMutableArray arrayWithArray:[fileString componentsSeparatedByString:#"\n"]];
fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"longitudes" ofType:#"txt"] encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *longitudeStringsArray = [NSMutableArray arrayWithArray:[fileString componentsSeparatedByString:#"\n"]];
// Now lets put them onto the map
int i; // Loop control
for (i=0; i<25; i++)
{
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc]init];
annotationCoordinate.latitude = [[latitudeStringsArray objectAtIndex:i]floatValue];
annotationCoordinate.longitude = [[longitudeStringsArray objectAtIndex:i]floatValue];
annotationPoint.coordinate = annotationCoordinate;
annotationPoint.title = [NSString stringWithFormat:#"Point %d",i];
annotationPoint.subtitle = [NSString stringWithFormat:#"%f, %f",[[latitudeStringsArray objectAtIndex:i]floatValue],[[longitudeStringsArray objectAtIndex:i]floatValue]];
[mapView addAnnotation:annotationPoint];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
The points appear as in the right places but they are the default red and not purple as I was trying to achieve. My understanding from the reading I have done is that the (MKAnnotationView) method should be called whenever an annotation point is created but it's not happening.
I know it's something fundamental that I'm missing but I have no idea what.
All assistance greatly appreciated.
Cheers,
If it's not called then you haven't set your ViewController as delegate for map view.