Delphi中TTMSFNCGeoCoding获取坐标后变量赋值无效问题求助
解决TTMSFNCGeoCoding异步调用后变量无值的问题
问题根源
TTMSFNCGeocoding的GetGeocoding方法是异步执行的——调用它之后,程序不会等待地理编码请求完成,而是直接跳去执行后续的showmessage代码。这时候回调函数还没被触发,ALongitude和ALatitude根本没被赋值,所以弹窗自然是空的。
解决方案
方案1:把后续逻辑移到回调函数内
既然回调是请求完成后才会触发的,把需要使用坐标的代码放到回调里,就能确保拿到有效数据:
Function TestFunction:Boolean; var ALongitude,ALatitude : string; FstartAdres : TTMSFNCMapsCoordinateRec; begin TMSFNCGeocoding1.GetGeocoding('New York', procedure(const ARequest : TTMSFNCGeocodingRequest; const ARequestResult : TTMSFNCCloudBaseRequestResult) begin // 先判断请求是否成功、是否有结果,避免出错 if ARequestResult.Success and (ARequest.Items.Count > 0) then begin FStartAdres := ARequest.Items[0].Coordinate.ToRec; ALongitude := FloatToStr(FstartAdres.Longitude); ALatitude := FloatToStr(FStartAdres.Latitude); // 所有需要用坐标的逻辑都放在这里 ShowMessage(ALongitude); ShowMessage(ALatitude); end; end); end;
方案2:用同步方式等待请求完成
如果必须在函数内同步拿到结果,可以用事件对象阻塞等待请求结束:
Function TestFunction:Boolean; var ALongitude,ALatitude : string; FstartAdres : TTMSFNCMapsCoordinateRec; WaitEvent: TEvent; begin WaitEvent := TEvent.Create(nil, True, False, ''); try TMSFNCGeocoding1.GetGeocoding('New York', procedure(const ARequest : TTMSFNCGeocodingRequest; const ARequestResult : TTMSFNCCloudBaseRequestResult) begin if ARequestResult.Success and (ARequest.Items.Count > 0) then begin FStartAdres := ARequest.Items[0].Coordinate.ToRec; ALongitude := FloatToStr(FstartAdres.Longitude); ALatitude := FloatToStr(FStartAdres.Latitude); end; WaitEvent.SetEvent; // 通知主线程请求完成 end); // 等待请求完成,超时时间可自行调整(示例为5000毫秒) if WaitEvent.WaitFor(5000) = wrSignaled then begin ShowMessage(ALongitude); ShowMessage(ALatitude); end else begin ShowMessage('请求超时'); end; finally WaitEvent.Free; end; end;
注意:这种方式会阻塞当前线程(如果是UI线程,界面会暂时卡住),只适合非UI线程或对卡顿不敏感的场景。
内容的提问来源于stack exchange,提问作者aaron versfeld
相关产品推荐
相关产品推荐

