Flutter 从地址获取坐标
有人能帮我找到一个地址的坐标吗Flutter 从地址获取坐标,flutter,search,coordinates,Flutter,Search,Coordinates,有人能帮我找到一个地址的坐标吗 我需要在文本框中输入地址并获取该地址的经度和纬度您可以复制粘贴并运行下面的完整代码 您可以使用软件包 代码片段 import 'package:geocoder/geocoder.dart'; // From a query final query = "1600 Amphiteatre Parkway, Mountain View"; var addresses = await Geocoder.local.findAddressesFromQuery(que
我需要在文本框中输入地址并获取该地址的经度和纬度您可以复制粘贴并运行下面的完整代码
您可以使用软件包
代码片段
import 'package:geocoder/geocoder.dart';
// From a query
final query = "1600 Amphiteatre Parkway, Mountain View";
var addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");
正在进行演示,最后一行是坐标
完整代码
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geocoder/services/base.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class AppState extends InheritedWidget {
const AppState({
Key key,
this.mode,
Widget child,
}) : assert(mode != null),
assert(child != null),
super(key: key, child: child);
final Geocoding mode;
static AppState of(BuildContext context) {
return context.inheritFromWidgetOfExactType(AppState);
}
@override
bool updateShouldNotify(AppState old) => mode != old.mode;
}
class GeocodeView extends StatefulWidget {
GeocodeView();
@override
_GeocodeViewState createState() => new _GeocodeViewState();
}
class _GeocodeViewState extends State<GeocodeView> {
_GeocodeViewState();
final TextEditingController _controller = new TextEditingController();
List<Address> results = [];
bool isLoading = false;
Future search() async {
this.setState(() {
this.isLoading = true;
});
try {
var geocoding = AppState.of(context).mode;
var results = await geocoding.findAddressesFromQuery(_controller.text);
this.setState(() {
this.results = results;
});
} catch (e) {
print("Error occured: $e");
} finally {
this.setState(() {
this.isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return new Column(children: <Widget>[
new Card(
child: new Padding(
padding: const EdgeInsets.all(10.0),
child: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
controller: _controller,
decoration: new InputDecoration(hintText: "Enter an address"),
),
),
new IconButton(
icon: new Icon(Icons.search), onPressed: () => search())
],
),
),
),
new Expanded(child: new AddressListView(this.isLoading, this.results)),
]);
}
}
class ReverseGeocodeView extends StatefulWidget {
ReverseGeocodeView();
@override
_ReverseGeocodeViewState createState() => new _ReverseGeocodeViewState();
}
class _ReverseGeocodeViewState extends State<ReverseGeocodeView> {
final TextEditingController _controllerLongitude =
new TextEditingController();
final TextEditingController _controllerLatitude = new TextEditingController();
_ReverseGeocodeViewState();
List<Address> results = [];
bool isLoading = false;
Future search() async {
this.setState(() {
this.isLoading = true;
});
try {
var geocoding = AppState.of(context).mode;
var longitude = double.parse(_controllerLongitude.text);
var latitude = double.parse(_controllerLatitude.text);
var results = await geocoding
.findAddressesFromCoordinates(new Coordinates(latitude, longitude));
this.setState(() {
this.results = results;
});
} catch (e) {
print("Error occured: $e");
} finally {
this.setState(() {
this.isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return new Column(children: <Widget>[
new Card(
child: new Padding(
padding: const EdgeInsets.all(10.0),
child: new Row(
children: <Widget>[
new Expanded(
child: new Column(
children: <Widget>[
new TextField(
controller: _controllerLatitude,
decoration: new InputDecoration(hintText: "Latitude"),
),
new TextField(
controller: _controllerLongitude,
decoration: new InputDecoration(hintText: "Longitude"),
),
],
),
),
new IconButton(
icon: new Icon(Icons.search), onPressed: () => search())
],
),
),
),
new Expanded(child: new AddressListView(this.isLoading, this.results)),
]);
}
}
class _MyAppState extends State<MyApp> {
Geocoding geocoding = Geocoder.local;
final Map<String, Geocoding> modes = {
"Local": Geocoder.local,
"Google (distant)": Geocoder.google("<API-KEY>"),
};
void _changeMode(Geocoding mode) {
this.setState(() {
geocoding = mode;
});
}
@override
Widget build(BuildContext context) {
return new AppState(
mode: this.geocoding,
child: new MaterialApp(
home: new DefaultTabController(
length: 2,
child: new Scaffold(
appBar: new AppBar(
title: new Text('Geocoder'),
actions: <Widget>[
new PopupMenuButton<Geocoding>(
// overflow menu
onSelected: _changeMode,
itemBuilder: (BuildContext context) {
return modes.keys.map((String mode) {
return new CheckedPopupMenuItem<Geocoding>(
checked: modes[mode] == this.geocoding,
value: modes[mode],
child: new Text(mode),
);
}).toList();
},
),
],
bottom: new TabBar(
tabs: [
new Tab(
text: "Query",
icon: new Icon(Icons.search),
),
new Tab(
text: "Coordinates",
icon: new Icon(Icons.pin_drop),
),
],
),
),
body: new TabBarView(children: <Widget>[
new GeocodeView(),
new ReverseGeocodeView(),
]),
),
),
),
);
}
}
class AddressTile extends StatelessWidget {
final Address address;
AddressTile(this.address);
final titleStyle =
const TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold);
@override
Widget build(BuildContext context) {
return new Padding(
padding: const EdgeInsets.all(10.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new ErrorLabel(
"feature name",
this.address.featureName,
fontSize: 15.0,
isBold: true,
),
new ErrorLabel("address lines", this.address.addressLine),
new ErrorLabel("country name", this.address.countryName),
new ErrorLabel("locality", this.address.locality),
new ErrorLabel("sub-locality", this.address.subLocality),
new ErrorLabel("admin-area", this.address.adminArea),
new ErrorLabel("sub-admin-area", this.address.subAdminArea),
new ErrorLabel("thoroughfare", this.address.thoroughfare),
new ErrorLabel("sub-thoroughfare", this.address.subThoroughfare),
new ErrorLabel("postal code", this.address.postalCode),
this.address.coordinates != null
? new ErrorLabel("", this.address.coordinates.toString())
: new ErrorLabel("coordinates", null),
]),
);
}
}
class AddressListView extends StatelessWidget {
final List<Address> addresses;
final bool isLoading;
AddressListView(this.isLoading, this.addresses);
@override
Widget build(BuildContext context) {
if (this.isLoading) {
return new Center(child: new CircularProgressIndicator());
}
return new ListView.builder(
itemCount: this.addresses.length,
itemBuilder: (c, i) => new AddressTile(this.addresses[i]),
);
}
}
class ErrorLabel extends StatelessWidget {
final String name, text;
final TextStyle descriptionStyle;
ErrorLabel(this.name, String text,
{double fontSize = 9.0, bool isBold = false})
: this.text = text ?? "Unknown $name",
this.descriptionStyle = new TextStyle(
fontSize: fontSize,
fontWeight: isBold ? FontWeight.bold : FontWeight.normal,
color: text == null ? Colors.red : Colors.black);
@override
Widget build(BuildContext context) {
return new Text(this.text, style: descriptionStyle);
}
}
导入'dart:async';
进口“包装:颤振/材料.省道”;
导入“包:geocoder/geocoder.dart”;
导入“包:geocoder/services/base.dart”;
void main()=>runApp(新的MyApp());
类MyApp扩展了StatefulWidget{
@凌驾
_MyAppState createState()=>new_MyAppState();
}
类AppState扩展了InheritedWidget{
常数AppState({
关键点,
这个模式,,
孩子,
}):assert(模式!=null),
断言(子项!=null),
super(key:key,child:child);
最终地理编码模式;
的静态AppState(BuildContext上下文){
返回context.inheritFromWidgetOfExactType(AppState);
}
@凌驾
bool updateShouldNotify(AppState old)=>mode!=old.mode;
}
类GeocodeView扩展StatefulWidget{
地理编码视图();
@凌驾
_GeocodeViewState createState()=>new_GeocodeViewState();
}
类_GeocodeViewState扩展状态{
_GeocodeViewState();
最终文本编辑控制器_控制器=新文本编辑控制器();
列出结果=[];
bool isLoading=false;
Future search()异步{
此.setState(){
this.isLoading=true;
});
试一试{
var geocoding=AppState.of(context.mode);
var results=await geocoding.findAddressesFromQuery(_controller.text);
此.setState(){
这个结果=结果;
});
}捕获(e){
打印(“发生错误:$e”);
}最后{
此.setState(){
this.isLoading=false;
});
}
}
@凌驾
小部件构建(构建上下文){
返回新列(子项:[
新卡(
孩子:新的填充物(
填充:常数边集全部(10.0),
孩子:新的一排(
儿童:[
新扩展(
孩子:新文本字段(
控制器:_控制器,
装饰:新输入装饰(hintText:“输入地址”),
),
),
新图标按钮(
图标:新图标(Icons.search),按下:()=>search()
],
),
),
),
新扩展(子项:新地址列表视图(this.isLoading,this.results)),
]);
}
}
类ReverseGeoCoDeviceView扩展StatefulWidget{
ReverseGeocodeView();
@凌驾
_ReverseGeoCoDeviceState createState()=>新建_ReverseGeoCoDeviceState();
}
类_ReverseGeocodeViewState扩展状态{
最终文本编辑控制器\u控制器长度=
新建TextEditingController();
最终文本编辑控制器_controllerlatude=新文本编辑控制器();
_ReverseGeoCoDeviceState();
列出结果=[];
bool isLoading=false;
Future search()异步{
此.setState(){
this.isLoading=true;
});
试一试{
var geocoding=AppState.of(context.mode);
var longitude=double.parse(_controllerLongitude.text);
var latitude=double.parse(_controllerLatitude.text);
var结果=等待地理编码
.findAddressesFromCoordinates(新坐标(纬度、经度));
此.setState(){
这个结果=结果;
});
}捕获(e){
打印(“发生错误:$e”);
}最后{
此.setState(){
this.isLoading=false;
});
}
}
@凌驾
小部件构建(构建上下文){
返回新列(子项:[
新卡(
孩子:新的填充物(
填充:常数边集全部(10.0),
孩子:新的一排(
儿童:[
新扩展(
子:新列(
儿童:[
新文本字段(
控制器:_controllerlatude,
装饰:新输入装饰(hintText:“纬度”),
),
新文本字段(
控制器:_控制器长度,
装饰:新输入装饰(hintText:“经度”),
),
],
),
),
新图标按钮(
图标:新图标(Icons.search),按下:()=>search()
],
),
),
),
新扩展(子项:新地址列表视图(this.isLoading,this.results)),
]);
}
}
类MyAppState扩展了状态{
地理编码地理编码=Geocoder.local;
最终贴图模式={
“本地”:Geocoder.Local,
“谷歌(远程)”:Geocoder.Google(“”),
};
void\u变更模式(地理编码模式){
此.setState(){
地理编码=模式;
});
}
@凌驾
小部件构建(构建上下文){
返回新的AppState(
模式:这是地理编码,
孩子:新材料pp(
主页:新的DefaultTabController(
长度:2,
儿童:新脚手架(
appBar:新的appBar(
标题:新文本(“地理编码器”),
行动:[
新弹出菜单按钮(
//溢出菜单
onSelected:_changeMode,
itemBuilder:(构建上下文){
返回模式.keys.map((字符串模式){
返回新的CheckedPopupMenuItem(
选中:模式[模式]==此。地理编码,
值:模式[模式],
子:新文本(模式),
);
}).toList();
},
),
],
底部:新选项卡栏(
选项卡:[
新标签(
文本:“查询”,
图标:新图标(Icons.search),
),
新标签(
正文:“坐标
TextFormField(
decoration: new InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15),
hintText: Strings.enter_your_house_number_street_etc,
hintStyle: TextStyle(
fontSize: 14,
color: AppColor.grey,
fontFamily: "Open Sans",
fontWeight: FontWeight.normal
)),
maxLines: 1,
controller: _address,
onTap: ()async{
// then get the Prediction selected
Prediction p = await PlacesAutocomplete.show(
context: context, apiKey: kGoogleApiKey,
onError: onError);
displayPrediction(p);
},
)
Future<Null> displayPrediction(Prediction p) async {
if (p != null) {
PlacesDetailsResponse detail = await _places.getDetailsByPlaceId(p.placeId);
var placeId = p.placeId;
lat = detail.result.geometry.location.lat;
long = detail.result.geometry.location.lng;
var address =detail.result.formattedAddress;
print(lat);
print(long);
print(address);
setState(() {
_address.text = address;
});
}
}