使用 Google 位置 API

发布于 2024-10-14 09:58:58 字数 372 浏览 2 评论 0原文

请原谅我的无知,但经过几个小时的搜索,我运气不佳。

无论如何,我正在尝试编写一个小型桌面应用程序,允许用户输入地址,然后以 GPS 坐标返回其大致位置。据我所知,Google 提供了一个地理编码 API[1],允许采用以下形式的请求:

http://maps.googleapis.com/maps/api/geocode/output?parameters

虽然我熟悉编写基本的 C Sharp 应用程序,但我真的不知道从哪里开始与此 API 交互。如果你们能提供任何帮助,我们将不胜感激。

Forgive me for my ignorance, but after several hours of searching, I'm having little luck.

Anyway, I am attempting to write a small desktop application that will allow a user to enter an address and then have their approximate location returned in GPS coordinates. From what I can tell, Google provides a geocoding API[1] that allows requests in the following form:

http://maps.googleapis.com/maps/api/geocode/output?parameters

While I'm familiar with writing basic C Sharp applications, I really have no idea where to start when it comes to interfacing with this API. Any help that you guys could provide would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情感失落者 2024-10-21 09:58:58

我编写了一个完整记录的 .NET 库 -

适用于 .NET 的 Google Maps Web Services API 包装器
https://github.com/maximn/google-maps/

//Directions
DirectionsRequest directionsRequest = new DirectionsRequest()
{
        Origin = "NYC, 5th and 39",
        Destination = "Philladephia, Chesnut and Wallnut",
};

        DirectionsResponse directions = MapsAPI.GetDirections(directionsRequest);

//Geocode
GeocodingRequest geocodeRequest = new GeocodingRequest()
{
        Address = "new york city",
};


GeocodingResponse geocode = MapsAPI.GetGeocode(geocodeRequest);

Console.WriteLine(geocode);

//Elevation
ElevationRequest elevationRequest = new ElevationRequest()
{
        Locations = new Location[] { new Location(54, 78) },
};


ElevationResponse elevation = MapsAPI.GetElevation(elevationRequest);

Console.WriteLine(elevation);

I wrote a fully documented .NET library -

Google Maps Web Services API wrapper for .NET
https://github.com/maximn/google-maps/

//Directions
DirectionsRequest directionsRequest = new DirectionsRequest()
{
        Origin = "NYC, 5th and 39",
        Destination = "Philladephia, Chesnut and Wallnut",
};

        DirectionsResponse directions = MapsAPI.GetDirections(directionsRequest);

//Geocode
GeocodingRequest geocodeRequest = new GeocodingRequest()
{
        Address = "new york city",
};


GeocodingResponse geocode = MapsAPI.GetGeocode(geocodeRequest);

Console.WriteLine(geocode);

//Elevation
ElevationRequest elevationRequest = new ElevationRequest()
{
        Locations = new Location[] { new Location(54, 78) },
};


ElevationResponse elevation = MapsAPI.GetElevation(elevationRequest);

Console.WriteLine(elevation);
極樂鬼 2024-10-21 09:58:58

这是一个示例代码,可以获取您想要的内容

using System;
using System.Web;
using System.Net;
using System.Runtime.Serialization.Json;

namespace GoogleMapsSample
{
    public class GoogleMaps
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static GeoResponse GetGeoCodedResults(string address)
        {
            string url = string.Format(
                    "http://maps.google.com/maps/api/geocode/json?address={0}®ion=dk&sensor=false",
                    HttpUtility.UrlEncode(address)
                    );
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse));
            var res = (GeoResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
            return res;
        }


    }

,您的帮助器类将是

 namespace GoogleMapsSample
{
    [DataContract]
    public class GeoResponse
    {
        [DataMember(Name = "status")]
        public string Status { get; set; }
        [DataMember(Name = "results")]
        public CResult[] Results { get; set; }

        [DataContract]
        public class CResult
        {
            [DataMember(Name = "geometry")]
            public CGeometry Geometry { get; set; }

            [DataContract]
            public class CGeometry
            {
                [DataMember(Name = "location")]
                public CLocation Location { get; set; }

                [DataContract]
                public class CLocation
                {
                    [DataMember(Name = "lat")]
                    public double Lat { get; set; }
                    [DataMember(Name = "lng")]
                    public double Lng { get; set; }
                }
            }
        }

        public GeoResponse()
        { }
    }


}

然后您可以在您的控件/winforms中使用此代码,如下所示,

            GeoResponse response = new GeoResponse();
            response = GoogleMaps.GetGeoCodedResults(TextBoxPostcode.Text);

并使用 StringBuilder 或其他任何东西在后面的代码上构建 JS

Here is a sample code to get what you want

using System;
using System.Web;
using System.Net;
using System.Runtime.Serialization.Json;

namespace GoogleMapsSample
{
    public class GoogleMaps
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static GeoResponse GetGeoCodedResults(string address)
        {
            string url = string.Format(
                    "http://maps.google.com/maps/api/geocode/json?address={0}®ion=dk&sensor=false",
                    HttpUtility.UrlEncode(address)
                    );
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse));
            var res = (GeoResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
            return res;
        }


    }

and you helper class would be

 namespace GoogleMapsSample
{
    [DataContract]
    public class GeoResponse
    {
        [DataMember(Name = "status")]
        public string Status { get; set; }
        [DataMember(Name = "results")]
        public CResult[] Results { get; set; }

        [DataContract]
        public class CResult
        {
            [DataMember(Name = "geometry")]
            public CGeometry Geometry { get; set; }

            [DataContract]
            public class CGeometry
            {
                [DataMember(Name = "location")]
                public CLocation Location { get; set; }

                [DataContract]
                public class CLocation
                {
                    [DataMember(Name = "lat")]
                    public double Lat { get; set; }
                    [DataMember(Name = "lng")]
                    public double Lng { get; set; }
                }
            }
        }

        public GeoResponse()
        { }
    }


}

Then you can use this code in your control/winforms like this

            GeoResponse response = new GeoResponse();
            response = GoogleMaps.GetGeoCodedResults(TextBoxPostcode.Text);

and build the JS on the code behind using StringBuilder or anyting else

离不开的别离 2024-10-21 09:58:58

Geocode API 相当简单,要从 api 获取纬度/经度,您只需要 3 个参数:输出、传感器和地址。

输出你想要的输出格式,json或xml(IIRC)

传感器应该是一个布尔值,指示天气或不是来自GPS芯片等传感器的值。

地址应该是您想要进行地理编码的地址(不要忘记对其进行网址编码)。

这是一个示例,我对我的办公室地址进行地理编码,并获取 JSON 响应:
http:// /maps.googleapis.com/maps/api/geocode/json?sensor=false&address=1+Maritime+Plaza+San+Francisco+CA

如果您导航到该位置,您应该会看到类似以下内容:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "1 Maritime Plaza, San Francisco, CA 94111, USA",
    "address_components": [ {
      "long_name": "1",
      "short_name": "1",
      "types": [ "street_number" ]
    }, {
      "long_name": "Maritime Plaza",
      "short_name": "Maritime Plaza",
      "types": [ "route" ]
    }, {
      "long_name": "San Francisco",
      "short_name": "San Francisco",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "San Francisco",
      "short_name": "San Francisco",
      "types": [ "administrative_area_level_3", "political" ]
    }, {
      "long_name": "San Francisco",
      "short_name": "San Francisco",
      "types": [ "administrative_area_level_2", "political" ]
    }, {
      "long_name": "California",
      "short_name": "CA",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "94111",
      "short_name": "94111",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 37.7953907,
        "lng": -122.3991803
      },
      "location_type": "ROOFTOP",
      "viewport": {
        "southwest": {
          "lat": 37.7922431,
          "lng": -122.4023279
        },
        "northeast": {
          "lat": 37.7985383,
          "lng": -122.3960327
        }
      }
    }
  } ]
}

如果您采取提供的经纬度并将其放置在 地图 你在我的地图上看到一个指针办公楼。

The Geocode API is rather simple, to get lat/lon from the api you only need to 3 params: output, sensor and address.

output the output format you want, json or xml (IIRC)

sensor should be a boolean indicating weather or not the value comes from a sensor such as a GPS chip.

address should be the address (don't forget to url encode it) you wish to geocode.

This is an example, where I geocode my office address, and get JSON in response:
http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=1+Maritime+Plaza+San+Francisco+CA

If you navigate to that you should see something like:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "1 Maritime Plaza, San Francisco, CA 94111, USA",
    "address_components": [ {
      "long_name": "1",
      "short_name": "1",
      "types": [ "street_number" ]
    }, {
      "long_name": "Maritime Plaza",
      "short_name": "Maritime Plaza",
      "types": [ "route" ]
    }, {
      "long_name": "San Francisco",
      "short_name": "San Francisco",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "San Francisco",
      "short_name": "San Francisco",
      "types": [ "administrative_area_level_3", "political" ]
    }, {
      "long_name": "San Francisco",
      "short_name": "San Francisco",
      "types": [ "administrative_area_level_2", "political" ]
    }, {
      "long_name": "California",
      "short_name": "CA",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "94111",
      "short_name": "94111",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 37.7953907,
        "lng": -122.3991803
      },
      "location_type": "ROOFTOP",
      "viewport": {
        "southwest": {
          "lat": 37.7922431,
          "lng": -122.4023279
        },
        "northeast": {
          "lat": 37.7985383,
          "lng": -122.3960327
        }
      }
    }
  } ]
}

If you take the lat/lon provided and place it on a map you see a pointer on my office building.

挽容 2024-10-21 09:58:58

我最近必须为我正在进行的一个项目构建一个商店定位器。在此之前我从未使用过任何 Google 或 Bing API。通过本教程,我能够很好地掌握 Location API。我建议您阅读本教程,在三个教程结束时您应该有一个很好的理解。

使用 Google Maps API 构建商店定位器 ASP.NET 应用程序(第 1 部分)

构建商店定位器 ASP.NET 应用程序使用 Google Maps API(第 2 部分)

使用 Google Maps API 构建商店定位器 ASP.NET 应用程序(第 3 部分)

I recently had to build a Store Locator for a project I am working on. I have never before this used any of the Google or Bing API's. Using this tutorial I was able to get a pretty good grasp of the Location API. I would suggest going through this tutorial and by the end of the three tutorials you should have a good understanding.

Building a Store Locator ASP.NET Application Using Google Maps API (Part 1)

Building a Store Locator ASP.NET Application Using Google Maps API (Part 2)

Building a Store Locator ASP.NET Application Using Google Maps API (Part 3)

手长情犹 2024-10-21 09:58:58

通过使用 GuigleAPI nuget 您可以简单地执行以下操作:

GoogleGeocodingAPI.GoogleAPIKey = "YOUR API KEY";
var result = await GoogleGeocodingAPI.GetCoordinatesFromAddressAsync("100 Market St, Southbank");
var latitude = result.Item1;
var longitude = result.Item2;

只需使用 nuget 命令安装它 < strong>Install-Package Easyforce.GuigleAPI 就可以开始了。

检查此答案以获取更多详细信息:
https://stackoverflow.com/a/44484010/1550202

By using GuigleAPI nuget you can simply do:

GoogleGeocodingAPI.GoogleAPIKey = "YOUR API KEY";
var result = await GoogleGeocodingAPI.GetCoordinatesFromAddressAsync("100 Market St, Southbank");
var latitude = result.Item1;
var longitude = result.Item2;

Just install it with the nuget command Install-Package Easyforce.GuigleAPI and you're good to go.

Check this answer for more details:
https://stackoverflow.com/a/44484010/1550202

一影成城 2024-10-21 09:58:58

如果您在 C# 中执行此操作,您将需要使用 HttpWebRequest 和 HttpWebResponse 类。您可以将参数化 URL(google API 调用)作为参数传递给 Create() 方法。我建议请求将数据作为 XML 数据返回。关闭连接(httpWResp.Close())后,您可以使用流读取器进行读取。请参阅有关 GetResponseStream() 方法的文档: http:// msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx

HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=1+Maritime+Plaza+San+Francisco+CA
");

HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
// 插入使用响应对象的代码。
HttpWResp.Close();

If your doing this in C#, you will want to use the HttpWebRequest and HttpWebResponse classes. You can pass the parameterized URL (google API call)as an argument to the Create() method. I would suggest requesting the data be returned as XML data. After you close the connection (httpWResp.Close()), you can read using a stream reader. See documentation on the GetResponseStream() method: http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx

HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=1+Maritime+Plaza+San+Francisco+CA
");

HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
// Insert code that uses the response object.
HttpWResp.Close();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文