顯示具有 UIWebView 標籤的文章。 顯示所有文章
顯示具有 UIWebView 標籤的文章。 顯示所有文章

2013年9月2日 星期一

使用WebView來顯示google街景地圖

緣起
2012年底新版的google map開始就支援街景地圖,
如今google官方也都有開api出來取用街景.
如果app不想讓user跳出程式來觀看google街景地圖,
也不想k一堆官方文件, 用WebView來嵌入是最快選擇了.


需求
有gps座標資料, 然後想要顯示該地區的街景


實作
比較老土的作法是把下面的string存成一份html檔案在local,
然後讀出html後轉成string再把經緯度給填上.

後來發現也不用這麼搞, 直接寫一份就對了!


NSString *htmlString = [NSString stringWithFormat:@"<html>\

                            <head>\
                            <meta id=\"viewport\" name=\"viewport\" content=\"width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\">\
                            <script src='http://maps.google.com/maps/api/js?sensor=false' type='text/javascript'></script>\
                            </head>\
                            <body onload=\"new google.maps.StreetViewPanorama(document.getElementById('p'),{position:new google.maps.LatLng(%f, %f)});\" style='padding:0px;margin:0px;'>\
                            <div id='p' style='height:460;width:320;'></div>\
                            </body>\
                            </html>",lat, lon];
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    webView.scalesPageToFit = YES;
    webView.scrollView.scrollEnabled = NO;
    webView.scrollView.bounces = NO;
    webView.delegate = self;
    [webView loadHTMLString:htmlString baseURL:nil];

完成圖如下:
























沒有很高深的技巧, 也不會太複雜.
分享給需要的人~

2010年8月25日 星期三

iPhone How to load a local HTML file and its images?

今天我需要從local加入一個html
而html又是附在各個不同語言的lproj資料夾下

現在有個抉擇來啦~
1. 是要各語言資料夾下都包含一份圖檔
2. 還是要共用一份resource就好了呢?
嗯~選1的話,還滿直覺的,當下不用什麼煩惱
但是未來要改個圖改個名可是要很辛苦的一份一份改捏
而且明明就可以共用的resource又何必複製好多份呢

好吧,所以我有一個資料夾完全是拿來放image resource
那UIWebView 這邊一開始我選擇loadRequest的method來做
不過圖片都是叉燒包...

很明顯我load html的路徑跟image是不同位置,當然行不通囉
嗯~換個邊思考一下,我們把url指到image那邊吧
看起來 loadHTMLString: baseURL: 這個method可以滿足我們的需求

1. 我們除了將html以iPhone常用的UTF8進行編碼,並且指定html的路徑
    (程式碼line 5,6,8,9,10)

2. image path要特別處理過才能在UIWebView下正常運作
    (程式碼line1,2,3)

3. 試試看吧~ it works like a charm!


NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"test" 
   ofType:@"html"];  

[webView loadHTMLString:[NSString stringWithContentsOfFile:filePath
                                         encoding:NSUTF8StringEncoding 
                                                     error:nil] 
             baseURL:[NSURL URLWithString: 
                  [NSString stringWithFormat:@"file:/%@//",imagePath]]];

參考資料:dBlog
              iphoneincubator
              brainwashinc
              第24個夏天後

內容回應