利用百度地图API得到指定城市的天气预报
利用百度地图车联网API,根据城市名查询天气的结果,并将天气图片下载到指定目录,利于后期显示。源代码中要用到的一些自定义函数、结构请在本站其他代码中查找。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
function TfrmMain.GetWeather(City: string): WeatherResults; var i, J, P, count: Integer; Url, PicPath: string; node: IXMLNode; XMLDoc: TXMLDocument; nodeList: IXMLNodeList; tStream: TFileStream; IdHTTP: TIdHTTP; begin XMLDoc := TXMLDocument.Create(Self); IdHTTP := TIdHTTP.Create; try Url := UrlEncode(Format( 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=xml&coord_type=wgs84&ak=A4c132a2db250e33cd1e2af37076ac28', [City])); try XMLDoc.XML.Text := IdHTTP.Get(Url); XMLDoc.Active := True; node := XMLDoc.DocumentElement.ChildNodes[3]; // <results> Result.error := XMLDoc.DocumentElement.ChildValues['error']; Result.status := XMLDoc.DocumentElement.ChildValues['status']; Result.date := XMLDoc.DocumentElement.ChildValues['date']; Result.currentCity := node.ChildValues['currentCity']; Result.pm25 := node.ChildValues['pm25']; nodeList := node.ChildNodes[1].ChildNodes; // <weather_data> count := nodeList.count; i := 0; for J := 1 to 4 do begin Result.Data[J].date := string(nodeList[i].NodeValue); Inc(i); Result.Data[J].dayPictureUrl := string(nodeList[i].NodeValue); Inc(i); Result.Data[J].nightPictureUrl := string(nodeList[i].NodeValue); Inc(i); Result.Data[J].weather := string(nodeList[i].NodeValue); Inc(i); Result.Data[J].wind := string(nodeList[i].NodeValue); Inc(i); Result.Data[J].temperature := string(nodeList[i].NodeValue); Inc(i); P := Pos('/images/', Result.Data[J].dayPictureUrl); PicPath := ExePath + copy(Result.Data[J].dayPictureUrl, P + 1, Length(Result.Data[J].dayPictureUrl) - P); PicPath := ReplaceChar(PicPath, '/', '\'); if not FileExists(PicPath) then begin tStream := TFileStream.Create(PicPath, fmCreate); try IdHTTP.Get(Result.Data[J].dayPictureUrl, tStream); // 開始下載 finally tStream.Free; end; end; P := Pos('/images/', Result.Data[J].nightPictureUrl); PicPath := ExePath + copy(Result.Data[J].nightPictureUrl, P + 1, Length(Result.Data[J].nightPictureUrl) - P); PicPath := ReplaceChar(PicPath, '/', '\'); if not FileExists(PicPath) then begin tStream := TFileStream.Create(PicPath, fmCreate); try IdHTTP.Get(Result.Data[J].nightPictureUrl, tStream); // 開始下載 finally tStream.Free; end; end; end; except abort; end; finally XMLDoc.Free; IdHTTP.Free; end; end; |