コード例 #1
0
        public async Task <String> GetPlaceName(double lat, double lon)
        {
            var client = new HttpClient();

            var response = await client.GetAsync(_googleBaseUrl + lat + "," + lon + "&key=AIzaSyBVKoHudUgMEwgt3mfNLgYUtEqSesNw8EU");

            //some logic
            var content = await response.Content.ReadAsStringAsync();

            var responseObject = JsonConvert.DeserializeObject <RootObject>(content);


            var firstResult = responseObject.results.FirstOrDefault();

            if (firstResult != null)
            {
                AddressComponent addressComponent = firstResult.address_components[2];
                string           longName         = addressComponent.long_name;
                return(longName);
            }
            else
            {
                return(null);
            }

            // foreach (var singleResult in responseObject.results)
            // {
            //     var location = singleResult.geometry.location;
            //     var latitude = location.lat;
            //     var longitude = location.lng;
            //     // Do whatever you want with them.
            //     Console.WriteLine(singleResult);
            // }
        }
コード例 #2
0
        public static AddressComponent componentParse(JsonObject addressComponent)
        {
            AddressComponent componetn = new AddressComponent();

            //国家
            componetn.country = addressComponent.GetNamedString("country");
            //国家代码
            componetn.countryCode = (int)addressComponent.GetNamedNumber("country_code");
            //省名
            componetn.province = addressComponent.GetNamedString("province");
            //城市名
            componetn.city = addressComponent.GetNamedString("city");
            //区县名
            componetn.district = addressComponent.GetNamedString("district");
            //行政区划代码
            componetn.adcode = addressComponent.GetNamedString("adcode");
            //街道名
            componetn.street = addressComponent.GetNamedString("street");
            //街道门牌
            componetn.streetNumber = addressComponent.GetNamedString("street_number");
            //和当前坐标的方向,有门牌号的时候返回数据
            componetn.direction = addressComponent.GetNamedString("direction");
            //和当前坐标的距离,有门牌号的时候返回数据
            componetn.distance = addressComponent.GetNamedString("distance");
            return(componetn);
        }
コード例 #3
0
        private static PlaceDetails CreatePlaceDetailsFromNode(XPathNavigator navNode)
        {
            XPathNavigator navNodeLocal = navNode.Clone();

            if (!navNodeLocal.MoveToFirstChild())
            {
                return(null);
            }

            PlaceDetails placedetails = new PlaceDetails();

            do
            {
                switch (navNodeLocal.LocalName)
                {
                case "formatted_address":
                    placedetails.Address.WorldAddress = navNodeLocal.Value;
                    break;

                case "formatted_phone_number":
                    placedetails.Phone = navNodeLocal.Value;
                    break;

                case "intl_phone_number":
                    placedetails.IntlPhone = navNodeLocal.Value;
                    break;

                case "rating":
                    placedetails.Rating = navNodeLocal.ValueAsDouble / 5 /* 5 star scale normalized to 0 -> 1 */;
                    break;

                case "url":
                    placedetails.LinkUri = new Uri(navNodeLocal.Value);
                    break;

                case "website":
                    placedetails.WebsiteUri = new Uri(string.Format("http:{1}", navNodeLocal.Value));
                    break;

                case "vicinity":     /* from places data */
                    placedetails.Address.Vicinity = navNodeLocal.Value;
                    HandlePlaceNode(placedetails as Place, navNodeLocal);
                    break;

                case "address_component":
                    AddressComponent addresscomponent = CreateAddressComponentFromNode(navNodeLocal);
                    if (addresscomponent.Types.Count > 0)
                    {
                        placedetails.Address.Components.Add(addresscomponent.Types[0], addresscomponent);
                    }
                    break;

                default:
                    HandlePlaceNode(placedetails as Place, navNodeLocal);
                    break;
                }
            }while (navNodeLocal.MoveToNext());

            return(placedetails);
        }
コード例 #4
0
        private static AddressComponent CreateAddressComponentFromNode(XPathNavigator navNode)
        {
            XPathNavigator navNodeLocal = navNode.Clone();

            if (!navNodeLocal.MoveToFirstChild())
            {
                return(null);
            }

            AddressComponent addresscomponent = new AddressComponent();

            do
            {
                switch (navNodeLocal.LocalName)
                {
                case "long_name":
                    addresscomponent.LongName = navNodeLocal.Value;
                    break;

                case "short_name":
                    addresscomponent.ShortName = navNodeLocal.Value;
                    break;

                case "type":
                    addresscomponent.Types.Add(navNodeLocal.Value);
                    break;
                }
            }while (navNodeLocal.MoveToNext());

            return(addresscomponent);
        }
コード例 #5
0
            private void SetValue(string strType, string strValueLong, string strValueShort = null)
            {
                AddressComponent addresscomponent = new AddressComponent();

                addresscomponent.LongName  = strValueLong;
                addresscomponent.ShortName = strValueShort ?? strValueLong;
                addresscomponent.Types.Add(strType);
                this.Components[strType] = addresscomponent;
            }
コード例 #6
0
        public static AddressComponent MapAddress(dynamic address)
        {
            var addressComponent = new AddressComponent
            {
                Address  = address?.address,
                City     = address?.city,
                Country  = address?.country,
                Province = address?.province
            };

            return(addressComponent);
        }
コード例 #7
0
ファイル: Ku_LocationService.cs プロジェクト: zhangvs/Map
        //通过aoi获得位置信息表(2,4)
        public Ku_LocationEntity GetLocationByAOI(IRepository db, Ku_LocationEntity locationData, GeocodesItem geo, Regeocode regeo, Aois aoi, int isRegeo)
        {
            locationData = db.FindList <Ku_LocationEntity>(t => t.RegeoId == aoi.id).FirstOrDefault();
            if (locationData != null)
            {
                //有此坐标,个数+1
                locationData.Count += 1;
                locationData.Modify(locationData.Id);
                db.Update <Ku_LocationEntity>(locationData);
            }
            else
            {
                AddressComponent addressComponent = regeo.addressComponent;

                double wxLon = 0, wxLat = 0, bdLon = 0, bdLat = 0;
                GDAPI.getCoordinate(aoi.location, out wxLat, out wxLon, out bdLat, out bdLon);

                string typeCode, typeName;
                GetTypeNameByCode(aoi.type, out typeCode, out typeName);
                //无此坐标,插入pos_location表
                locationData = new Ku_LocationEntity()
                {
                    Address   = regeo.formatted_address,
                    Province  = addressComponent.province,
                    City      = addressComponent.city,
                    CityCode  = addressComponent.citycode,
                    District  = addressComponent.district,
                    AdCode    = addressComponent.adcode,
                    Township  = addressComponent.township,
                    Location  = aoi.location,
                    wxLon     = Convert.ToDecimal(wxLon),
                    wxLat     = Convert.ToDecimal(wxLat),
                    bdLon     = Convert.ToDecimal(bdLon),
                    bdLat     = Convert.ToDecimal(bdLat),
                    _Level    = geo.level,
                    IsRegeo   = isRegeo,
                    RegeoId   = aoi.id,
                    RegeoName = aoi.name,
                    Area      = aoi.area,//存在字母转换失败decimal“山东省临沂市平邑县地方镇九间棚”
                    TypeCode  = typeCode,
                    TypeName  = typeName,
                    Count     = 1
                };
                locationData.Create();
                db.Update <Ku_LocationEntity>(locationData);
            }
            return(locationData);
        }
コード例 #8
0
        public AddressComponent getAddress()
        {
            INWindow         inWindow = this.dataService.INWindow as INWindow;
            AddressComponent result;

            if (inWindow != null)
            {
                AddressComponent address = new AddressComponent();
                result = address;
            }
            else
            {
                result = null;
            }
            return(result);
        }
コード例 #9
0
        public static AddressComponent AnalyticalData_obj(string jsonData)
        {
            var obj = JsonConvert.DeserializeObject <ResultData_Items>(jsonData);

            if (obj.status == "OK")
            {
                AddressComponent items = obj.result.addressComponent;
                //Console.WriteLine(items.city);
                return(items);
            }
            else
            {
                MessageBox.Show(obj.status + "**未能获取信息!", "请求异常");
                return(null);
            }
        }
コード例 #10
0
ファイル: SearchService.cs プロジェクト: snoww/roki
        private CultureInfo GetLocalCulture(IEnumerable <AddressComponent> components)
        {
            AddressComponent country = components.FirstOrDefault(c => c.Types.Contains("country", StringComparer.Ordinal));

            if (country == null)
            {
                return(null);
            }

            try
            {
                using JsonDocument json = JsonDocument.Parse(File.ReadAllText("./data/countries.json"));
                string lang = json.RootElement.GetProperty(country.ShortName).GetProperty("languages")[0].GetString();
                return(new CultureInfo(lang !));
            }
            catch (Exception)
            {
                Logger.Warn("Could not find culture for {Culture}", country.LongName);
                return(null);
            }
        }
コード例 #11
0
 public ForwardGeoCodeInput(AddressComponent input
                            , string formattedAddress)
 {
     Input            = input;
     FormattedAddress = formattedAddress;
 }
        /// <summary>
        /// Addresses the component generator.
        /// </summary>
        /// <param name="addressId">The address identifier.</param>
        /// <param name="profileDefinition">The profile definition.</param>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A <see cref="AddressComponent" />
        /// </returns>
        internal static async Task <AddressComponent> AddressComponentGenerator(string addressId, ProfileDefinition profileDefinition, CommercePipelineExecutionContext context)
        {
            // map properties to AddressComponent
            var addressType      = context.GetPolicy <ProfilePropertiesPolicy>().AddressType;
            var addressComponent = new AddressComponent {
                Name = addressType
            };

            try
            {
                var sqlContext = ConnectionHelper.GetProfilesSqlContext(context.CommerceContext);
                var address    = await sqlContext.GetAddress(addressId).ConfigureAwait(false);

                addressComponent.Id = addressId;

                var addressProperties = context.GetPolicy <ProfilePropertiesMappingPolicy>().AddressProperties;
                var details           = new EntityView {
                    Name = "Details"
                };

                foreach (var property in profileDefinition.Properties)
                {
                    if (addressProperties.ContainsKey($"{property.GroupName}.{property.Name}"))
                    {
                        var rawValue = address[property.ColumnName] as string;
                        if (string.IsNullOrEmpty(rawValue) || property.Name.Equals("address_id", StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        var addressProperty = addressProperties[$"{property.GroupName}.{property.Name}"];
                        var propertyInfo    = addressComponent.Party.GetType().GetProperty(addressProperty, BindingFlags.Public | BindingFlags.Instance);
                        if (propertyInfo != null && propertyInfo.CanWrite)
                        {
                            propertyInfo.SetValue(addressComponent.Party, rawValue, null);
                        }
                        else
                        {
                            TypeConverter typeConverter = TypeDescriptor.GetConverter(property.OriginalType);
                            var           profileValue  = typeConverter.ConvertFromString(rawValue);
                            details.Properties.Add(new ViewProperty {
                                Name = addressProperty, RawValue = profileValue
                            });
                        }
                    }
                }

                if (details.Properties.Any())
                {
                    addressComponent.View.ChildViews.Add(details);
                }
            }
            catch (Exception ex)
            {
                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "EntityNotFound",
                    new object[] { addressId, ex },
                    $"Address { addressId } was not found.").ConfigureAwait(false);

                return(null);
            }

            return(addressComponent);
        }
コード例 #13
0
        public async Task <IActionResult> Index()
        {
            var user = await _userManager.GetUserAsync(User); // Authenticated User

            if (user == null)
            {
                ViewBag.isNearMe        = "false";
                ViewBag.isAuthenticated = "false";
                return(View());
            }

            await _hubContext.Clients.All.SendAsync("Notify", $"Home page loaded at: {DateTime.Now}");

            var users       = _userManager.Users.ToList(); // All Users
            var userAddress = _db.UserAddresses.FirstOrDefault(uad => uad.UserId == user.Id);

            AddressComponent   userCounty     = null;
            Location           userLocation   = null;
            List <UserMapData> allUserMapData = new List <UserMapData>();

            ViewBag.googleApiKey = _applicationSettings.GoogleApiKey;

            if (userAddress != null)
            {
                string userAddressQuery = "";
                userAddressQuery = GetAddressQuery(userAddress);

                if (userAddressQuery != "")
                {
                    userLocation = GetCoords(userAddressQuery, ViewBag.googleApiKey);
                    userCounty   = GetCounty(userAddressQuery, ViewBag.googleApiKey);

                    List <Location> positions = new List <Location>();
                    Double          distance  = 0;

                    foreach (var member in users)
                    {
                        // Don't load personal pins
                        if (member.Id == user.Id)
                        {
                            continue;
                        }

                        string memberAddressQuery = "";
                        var    memberAddress      = _db.UserAddresses.FirstOrDefault(uad => uad.UserId == member.Id);
                        var    pins = _db.UserPins.Where(uid => uid.UserId == member.Id).ToList();

                        if (memberAddress != null && (pins != null && pins.Count > 0))
                        {
                            memberAddressQuery = GetAddressQuery(memberAddress);
                            if (memberAddressQuery != "")
                            {
                                Location memberLocation = GetCoords(memberAddressQuery, ViewBag.googleApiKey);
                                distance = HaversineDistance(userLocation, memberLocation);

                                positions.Add(memberLocation);

                                if (positions.Count > 1)
                                {
                                    foreach (var position in positions)
                                    {
                                        var latIsEqual = Math.Abs(position.lat - memberLocation.lat) < Double.Epsilon;
                                        var lngIsEqual = Math.Abs(position.lng - memberLocation.lng) < Double.Epsilon;

                                        if (latIsEqual && lngIsEqual)
                                        {
                                            Location locOffset = GetOffset(memberLocation.lat, memberLocation.lng);

                                            memberLocation = new Location
                                            {
                                                lat = locOffset.lat,
                                                lng = locOffset.lng
                                            };
                                        }
                                    }
                                }

                                if (distance < 50)
                                {
                                    Location location = new Location
                                    {
                                        lat = memberLocation.lat,
                                        lng = memberLocation.lng
                                    };

                                    // Need to ecnrypt UserId
                                    UserMapData userMapData = new UserMapData
                                    {
                                        UserId        = member.Id,
                                        UserName      = member.UserName,
                                        Location      = location,
                                        LocationColor = GetLocationColor(pins)
                                    };

                                    allUserMapData.Add(userMapData);
                                }
                            }
                        }
                    }
                }
            }

            if (allUserMapData.Count == 0)
            {
                ViewBag.isNearMe = "false";
                ViewBag.noPins   = "true";
                return(View());
            }

            ViewBag.userCounty   = userCounty.long_name;
            ViewBag.userLocation = userLocation;
            ViewBag.isNearMe     = "true";
            return(View(allUserMapData));
        }
コード例 #14
0
        static public LocationResults getLocationFromGoogle(string s)
        {
            // string url = "http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
            string url = string.Format(@"https://maps.google.com/maps/api/geocode/xml?key={1}&address={0}&sensor=false", s, __API_KEY);

            XmlDocument doc = MakeRequest(url);

            /*
             * <?xml version="1.0" encoding="UTF-8"?>
             * <GeocodeResponse>
             *  <status>OK</status>
             *  <result>
             *      <type>street_address</type>
             *      <formatted_address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</formatted_address>
             *      <address_component>
             *          <long_name>1600</long_name>
             *          <short_name>1600</short_name>
             *          <type>street_number</type>
             *          </address_component>
             *      <address_component>
             *          <long_name>Amphitheatre Parkway</long_name>
             *          <short_name>Amphitheatre Pkwy</short_name>
             *          <type>route</type>
             *      </address_component>
             *      <address_component>
             *          <long_name>Mountain View</long_name>
             *          <short_name>Mountain View</short_name>
             *          <type>locality</type>
             *          <type>political</type>
             *      </address_component>
             *      <address_component>
             *          <long_name>Santa Clara County</long_name>
             *          <short_name>Santa Clara County</short_name>
             *          <type>administrative_area_level_2</type>
             *          <type>political</type>
             *      </address_component>
             *      <address_component>
             *          <long_name>California</long_name>
             *          <short_name>CA</short_name>
             *          <type>administrative_area_level_1</type>
             *          <type>political</type>
             *      </address_component>
             *      <address_component>
             *          <long_name>United States</long_name>
             *          <short_name>US</short_name>
             *          <type>country</type>
             *          <type>political</type>
             *      </address_component>
             *      <address_component>
             *          <long_name>94043</long_name>
             *          <short_name>94043</short_name>
             *          <type>postal_code</type>
             *      </address_component>
             *      <geometry>
             *          <location>
             *              <lat>37.4223434</lat>
             *              <lng>-122.0843689</lng>
             *          </location>
             *          <location_type>ROOFTOP</location_type>
             *          <viewport>
             *              <southwest>
             *                  <lat>37.4209944</lat>
             *                  <lng>-122.0857179</lng>
             *              </southwest>
             *              <northeast>
             *                  <lat>37.4236924</lat>
             *                  <lng>-122.0830199</lng>
             *              </northeast>
             *          </viewport>
             *      </geometry>
             *      <place_id>ChIJ2eUgeAK6j4ARbn5u_wAGqWA</place_id>
             *  </result>
             * </GeocodeResponse>
             */

            double          dbl        = 0;
            LocationResults result     = new LocationResults();
            XmlNode         statusnode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/status");

            if (statusnode != null)
            {
                if (statusnode.InnerText != "OK")
                {
                    throw new ArgumentException("Bad status received " + statusnode.InnerText);
                }
            }

            XmlNode latnode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat");

            if (latnode != null && double.TryParse(latnode.InnerText, out dbl))
            {
                result.Lat = dbl;
            }

            XmlNode lngnode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng");

            if (lngnode != null && double.TryParse(lngnode.InnerText, out dbl))
            {
                result.Lon = dbl;
            }

            XmlNode pcnnode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/result/geometry/location_type");

            if (pcnnode != null)
            {
                result.Precision = pcnnode.InnerText;
            }

            XmlNode plcnode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/result/place_id");

            if (plcnode != null)
            {
                result.PlaceID = plcnode.InnerText;
            }

            XmlNode typenode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/result/type");

            if (typenode != null)
            {
                result.FormattedAs = typenode.InnerText;
            }

            XmlNode fmtnode = doc.DocumentElement.SelectSingleNode("/GeocodeResponse/result/formatted_address");

            if (fmtnode != null)
            {
                result.Formatted = fmtnode.InnerText;
            }

            XmlNodeList compnode = doc.DocumentElement.SelectNodes("/GeocodeResponse/result/address_component");

            foreach (XmlNode node in compnode)
            {
                AddressComponent component = new AddressComponent();
                XmlNode          lnmnode   = node.SelectSingleNode("long_name");
                if (lnmnode != null)
                {
                    component.Long = lnmnode.InnerText;
                }

                XmlNode snmnode = node.SelectSingleNode("short_name");
                if (snmnode != null)
                {
                    component.Short = snmnode.InnerText;
                }

                XmlNodeList catnode = node.SelectNodes("type");
                foreach (XmlNode cat1node in catnode)
                {
                    component.Category.Add(cat1node.InnerText);
                }

                result.Components.Add(component);
            }


            return(result);
        }
コード例 #15
0
        private static string LeeNombreTipo(Result res, string tipo)
        {
            AddressComponent address = res.address_components.Find(ac => ac.types.Contains(tipo));

            return(address?.long_name ?? string.Empty);
        }