2
1

More than 5 years have passed since last update.

Xamarin.iOS Maps Static APIを利用した地図画像生成

Last updated at Posted at 2018-07-06

自作のランチアプリを作っている時に、だいたいこの辺みたいな感じで、GoogleMapのピン付き画像が欲しかったので使用してみた。

どんな感じかと言うと、

ピンを立てたい位置に照準を合わせて、

IMG_0166.PNG

確定ボタン的な何かをタップすると、

スクリーンショット 2018-07-06 19.12.32.png

照準を合わせたところにピンがたった画像が生成されるといった感じ。

実装

1.表示されているGoogleMapの中心座標を渡す


CGPoint point = Mapview.Center;
Mapview.Projection.CoordinateForPoint(point);

2.Maps Static APIに、GoogleMapの中心座標のLatitudeLongitudeを渡し叩く


string url = Uri.EscapeUriString("https://maps.google.com/maps/api/staticmap?markers=color:red|" + $"{lat},{lng}" + "&zoom=16&size=" + 207 + "x" + $"{Math.Floor(this.screenShotViewWitdh)}" + "&sensor=true");
NSUrl googlmapsStaticMapApi = new NSUrl(url);

3.NSData.FromUrlを使い、画像データを取得する


return UIImage.LoadFromData(NSData.FromUrl(googlmapsStaticMapApi));

4.前の画面に画像データを渡す

public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            if(IsMovingFromParentViewController){
                var parentVc = NavigationController.ChildViewControllers;
                //HACK: コントローラー名でなおかつそのコントローラーが生きている状態という条件にした方が良さそう
                var childvc = ParentViewController.ChildViewControllers[1] as UpLoadDataViewController;
                childvc.setMapImage(MakeStaticGoogleMap());
                childvc.setLatLng(lat, lng);
            }    
        }

5.渡ってきた画像データをImageViewに入れる


public async override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);
            if (map != null)
            {
                StreetAddressImageView.Image = map;
            }
            if (shop != null)
            {
               //未実装
            }
        }

画像生成部分の全体


public UIImage MakeStaticGoogleMap(){
            CGPoint point = Mapview.Center;
            CLLocationCoordinate2D coordinate2D = Mapview.Projection.CoordinateForPoint(point);
            lat = coordinate2D.Latitude;
            lng = coordinate2D.Longitude;
            string url = Uri.EscapeUriString("https://maps.google.com/maps/api/staticmap?markers=color:red|" + $"{lat},{lng}" + "&zoom=16&size=" + 207 + "x" + $"{Math.Floor(this.screenShotViewWitdh)}" + "&sensor=true"); //$"{Math.Floor(this.screenShotViewHeight)}"
            NSUrl googlmapsStaticMapApi = new NSUrl(url);
            return UIImage.LoadFromData(NSData.FromUrl(googlmapsStaticMapApi));
        }

StackOverFlowのどっかにあった質問をみてやったのですが忘れてしまったので思い出したら貼っておきます。。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1