Пример #1
0
        // GET: Friends
        public ActionResult Index(string DistanceSearch, string FromWhere, string FromWhereCity)
        {
            GoogleMapsAPI maps = GoogleMapsAPI.getInstance();

            // retrieve the current Client's IP
            string clientIp = getUsersIP();

            // use IpApi to retrieve the client's location
            // or use search city
            string lat = null, lng = null;

            if (!String.IsNullOrEmpty(FromWhere) && FromWhere == "other" && !String.IsNullOrEmpty(FromWhereCity))
            {
                string[] location = maps.getAddressInfoByStreet(FromWhereCity);
                if (location != null)
                {
                    lat = location[0];
                    lng = location[1];
                }
            }
            if (String.IsNullOrEmpty(lat) || String.IsNullOrEmpty(lng))
            {
                string location = new WebClient().DownloadString(String.Format("https://ipapi.co/{0}/latlong/", clientIp));
                lat = location.Substring(0, location.IndexOf(",")).Trim();
                lng = location.Substring(lat.Length + 1).Trim();
            }


            // check distance from search
            double dist = 10000;

            if (!String.IsNullOrEmpty(DistanceSearch))
            {
                Double.TryParse(DistanceSearch, out dist);
            }

            //set up for query call
            var pLat  = new SqlParameter("p_lat", lat);
            var pLng  = new SqlParameter("p_lng", lng);
            var pDist = new SqlParameter("p_dist", dist);

            // call the procedure
            var friendList = db.Database.SqlQuery <FriendWithDistanceViewModel>("exec geodist @p_lat, @p_lng, @p_dist", pLat, pLng, pDist);

            // setup info for display
            string address = maps.getAddressInfoByLocation(lat, lng);

            ViewBag.IntellisenseScript = GoogleMapsAPI.getIntellisenseScriptURL();

            FriendListViewModel viewModel = new FriendListViewModel()
            {
                friendList = friendList,
                clientIp   = clientIp,
                lat        = lat,
                lng        = lng,
                location   = address
            };

            return(View(viewModel));
        }
Пример #2
0
    void Start()
    {
        Debug.Log("Maps start");
        User = PlayerPrefs.GetString("User");
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://memhunter-c91dd.firebaseio.com/");

        // Get the root reference location of the database.
        reference = FirebaseDatabase.DefaultInstance.RootReference;

        Instance = this;
        //StartCoroutine(StartLocationService());
        getNewURL();
    }
        public async Task GetPositionFromKnownAddressTest()
        {
            string   addressString = "3 Russel Street, GlandStone, Invercargill, New Zealand";
            Position position      = await GoogleMapsAPI.GetPositionFromKnownAddress(addressString);

            Assert.AreEqual(-46.3, position.Latitude, 0.1);
            //addressString = "140 Main Street, Gore, New Zealand";
            //position = await GoogleMapsAPI.GetPositionFromKnownAddress(addressString);
            //Assert.AreEqual(-46.1, position.Latitude, 0.1);
            addressString = "Invercargill, Russel st 3 ";
            position      = await GoogleMapsAPI.GetPositionFromKnownAddress(addressString);

            Assert.AreEqual(0, position.Latitude, 0.5);
        }
Пример #4
0
        // GET: Friends/Add
        public ActionResult Add(int?message)
        {
            FriendAddViewModel viewModel = new FriendAddViewModel();

            ViewBag.IntellisenseScript = GoogleMapsAPI.getIntellisenseScriptURL();

            if (message != null)
            {
                // safeguard range
                int index = message >= messages.Length || message < 0 ? messages.Length - 1 : (int)message;
                viewModel.message = messages[index];
            }

            return(View(viewModel));
        }
 public void SortWaypointsTest()
 {
     string[] waypoints =
     {
         $"45.1%2C30.1",
         $"45.3%2C30.3",
         $"45.3%2C30.1"
     };
     foreach (string line in waypoints)
     {
         System.Console.WriteLine(line);
     }
     GoogleMapsAPI.SortWaypoints(waypoints);
     Assert.AreEqual("45.3%2C30.1", waypoints[1]);
 }
Пример #6
0
        //InitPins() should be called before this method, _waypoints is added in InitPins()
        //A method that let's google handle the directions, shortest path etc.
        private async void MapDirections(string message = "")
        {
            //for diagnostic
            numberOfAPICalls++;
            Console.WriteLine($"{message} Number Of API Calls: #{numberOfAPICalls}");

            map.Polylines.Clear();
            if (_currentLocation == null)
            {
                _currentLocation = await Geolocation.GetLastKnownLocationAsync();
            }
            Position lastKnownPosition = new Position(_currentLocation.Latitude, _currentLocation.Longitude);

            if (_waypoints.Count > 0 && App.CheckIfInternet())
            {
                _invoicesCollection.Clear();
                _direction = await GoogleMapsAPI.MapDirectionsWithWaypoints(lastKnownPosition, _waypoints.ToArray());

                //Only create a line if it returns something from google
                if (_direction.Status != "ZERO_RESULTS" && _direction.Routes.Count > 0)
                {
                    List <Position> directionPolylines = PolylineHelper.Decode(_direction.Routes[0].OverviewPolyline.Points).ToList();

                    CreatePolylinesOnMap(directionPolylines);

                    foreach (int order in GoogleMapsAPI._waypointsOrder)
                    {
                        _invoicesCollection.Add(_invoices[order]);
                    }

                    DeliveryItemView.ItemsSource = _invoicesCollection;
                }
                else
                {
                    await DisplayAlert("Oops", "Unable to map the directions, please try to use internet connections or restart the app", "OK");
                }
            }
            else if (_waypoints.Count() == 0 && App.CheckIfInternet())
            {
                _direction = await GoogleMapsAPI.MapDirectionsNoWaypoints(lastKnownPosition);

                if (_direction.Status != "ZERO_RESULTS" && _direction.Routes.Count > 0)
                {
                    List <Position> directionPolylines = PolylineHelper.Decode(_direction.Routes[0].OverviewPolyline.Points).ToList();
                    CreatePolylinesOnMap(directionPolylines);
                }
            }
        }
Пример #7
0
        private async void CheckEndPoint()
        {
            if (EndPoint == Preferences.Get("EndPoint", ""))
            {
                return;
            }
            Position position = await GoogleMapsAPI.GetPositionFromKnownAddress(_endPoint);

            bool isSuccess = !(position.Latitude == 0 && position.Longitude == 0);

            if (isSuccess)
            {
                Preferences.Set("EndPoint", EndPoint);
                Preferences.Set("EndPointGeoWaypoint", $"{position.Latitude}%2C{position.Longitude}");
                GoogleMapsAPI.DestinationAddress  = EndPoint;
                GoogleMapsAPI.DestinationPosition = position;
            }

            Validate(() => !isSuccess, "Set the End Point as " + _endPoint, "Message");
            Validate(() => isSuccess, "The address is not valid, Please try again", "Message"); // Message is not a real property name
        }
Пример #8
0
        public ActionResult Add(FriendAddViewModel viewModel)
        {
            GoogleMapsAPI maps = GoogleMapsAPI.getInstance();

            string[] location = maps.getAddressInfoByStreet(viewModel.friend.street);

            if (maps.statusCode == GoogleMapsAPI.RESPONSE_OK)
            {
                // grab the latitude and longitude and store them
                viewModel.friend.latitude     = location[0];
                viewModel.friend.longitude    = location[1];
                viewModel.friend.full_address = location[2];

                // check if the friend already exists
                var check = (from friendList in db.friends
                             where friendList.full_address == viewModel.friend.full_address &&
                             friendList.name == viewModel.friend.name
                             select friendList).FirstOrDefault();

                if (check != null)
                {
                    return(RedirectToAction("Add", new { message = 0 }));
                }

                db.friends.Add((Friend)viewModel.friend);
                db.SaveChanges();
            }
            else if (maps.statusCode == GoogleMapsAPI.RESPONSE_NOT_FOUND)
            {
                return(RedirectToAction("Add", new { message = 1 }));
            }
            else
            {
                return(RedirectToAction("Add", new { message = 2 }));
            }

            return(RedirectToAction("Index"));
        }
Пример #9
0
        //A method that let's google handle the directions, shortest path etc.
        private async void MapDirections(string message = "")
        {
            //for diagnostic
            numberOfAPICalls++;
            Console.WriteLine($"{message} Number Of API Calls: #{numberOfAPICalls}");

            map.Polylines.Clear();
            if (_currentLocation == null)
            {
                _currentLocation = await Geolocation.GetLastKnownLocationAsync();
            }
            Position lastKnownPosition = new Position(_currentLocation.Latitude, _currentLocation.Longitude);

            // Position lastKnownPosition = new Position(-46.3, 168);
            if (_waypoints.Count > 0 && App.CheckIfInternet())
            {
                _invoicesCollection.Clear();

                if (_waypoints.Count > MAX_WAYPOINTS)
                {
                    GoogleMapsAPI.SortWaypoints(lastKnownPosition, _waypoints.ToArray());
                    List <Invoice> tempInvoice = new List <Invoice>();
                    for (int i = 0; i < GoogleMapsAPI._waypointsOrder.Count; i++)
                    {
                        tempInvoice.Add(_invoices[GoogleMapsAPI._waypointsOrder[i]]);
                    }
                    _invoices = tempInvoice;
                }

                for (int i = 0; i < _waypoints.Count; i += MAX_WAYPOINTS)
                {
                    string   destinationWaypoint;
                    int      waypointCountLeft = _waypoints.Count - i;
                    string[] orderedWaypoints;
                    if (waypointCountLeft > MAX_WAYPOINTS)
                    {
                        orderedWaypoints = new string[MAX_WAYPOINTS];
                        _waypoints.CopyTo(i, orderedWaypoints, 0, MAX_WAYPOINTS);
                        destinationWaypoint = orderedWaypoints[orderedWaypoints.Count() - 1];
                    }
                    else
                    {
                        orderedWaypoints = new string[waypointCountLeft];
                        _waypoints.CopyTo(i, orderedWaypoints, 0, waypointCountLeft);
                        if ((destinationWaypoint = Preferences.Get("EndPointGeoWaypoint", string.Empty)) == "")
                        {
                            destinationWaypoint = orderedWaypoints[orderedWaypoints.Count() - 1];
                        }
                    }


                    _direction = await GoogleMapsAPI.MapDirectionsWithWaypoints(lastKnownPosition, destinationWaypoint, orderedWaypoints);

                    string[] newCurrentPosition = orderedWaypoints[orderedWaypoints.Count() - 1].Split(new string[] { "%2C" }, StringSplitOptions.None);
                    lastKnownPosition = new Position(Convert.ToDouble(newCurrentPosition[0]), Convert.ToDouble(newCurrentPosition[1]));

                    //Only create a line if it returns something from google
                    if (_direction.Status != "ZERO_RESULTS" && _direction.Routes.Count > 0)
                    {
                        AddPolyLine();

                        foreach (int order in GoogleMapsAPI._waypointsOrder)
                        {
                            _invoicesCollection.Add(_invoices[order + i]);
                        }
                    }
                    else
                    {
                        await DisplayAlert("Oops", "Unable to map the directions, Please make sure the address entered is legit", "OK");
                    }
                }
                DeliveryItemView.ItemsSource = _invoicesCollection;
            }
            else if (_waypoints.Count() == 0 && App.CheckIfInternet())
            {
                string destinationPoint;
                if ((destinationPoint = Preferences.Get("EndPointGeoWaypoint", string.Empty)) == "")
                {
                    return;
                }
                _direction = await GoogleMapsAPI.MapDirectionsNoWaypoints(lastKnownPosition, destinationPoint);

                if (_direction.Status != "ZERO_RESULTS" && _direction.Routes.Count > 0)
                {
                    AddPolyLine();
                }
            }
        }
Пример #10
0
        //initialize markers on map and position into _waypoints
        private async Task <bool> InitPins()
        {
            _pins.Clear();
            map.Pins.Clear();
            _waypoints.Clear();

            for (int i = 0; i < _invoiceSQLite.Count; i++)
            {
                ContactSQLite customerContact = App.ContactDatabase.GetContactByID(_invoiceSQLite[i].ContactID);
                Position      position;

                if (!customerContact.Latitude.HasValue)
                {
                    //Get better format from address
                    #region Format the Address
                    string fullAddress = customerContact.Address;
                    if (fullAddress == "")
                    {
                        continue;
                    }
                    else if (customerContact.City != "")
                    {
                        fullAddress += $", {customerContact.City}";
                    }
                    fullAddress += $", New Zealand";
                    #endregion

                    if (App.CheckIfInternet())
                    {
                        //Get location by calling google geolocation API / each invoice
                        position = await GoogleMapsAPI.GetPositionFromKnownAddress(fullAddress);

                        customerContact.Latitude  = position.Latitude;
                        customerContact.Longitude = position.Longitude;
                    }
                    else
                    {
                        try {
                            Location location = Geocoding.GetLocationsAsync(fullAddress).Result.FirstOrDefault();
                            position = new Position(location.Latitude, location.Longitude);
                            customerContact.Latitude  = position.Latitude;
                            customerContact.Longitude = position.Longitude;
                        }
                        catch
                        {
                            position = new Position(0, 0);
                            await DisplayAlert("Alert", String.Format("Couldnt map the position of {0}", _invoiceSQLite[i].InvoiceNumber), "OK");
                        }
                    }

                    if (customerContact.Latitude.HasValue)
                    {
                        App.ContactDatabase.UpdateContactPosition(customerContact);
                    }
                }
                else
                {
                    position = new Position(customerContact.Latitude.Value, customerContact.Longitude.Value);
                }

                if (position.Latitude != 0 && position.Longitude != 0)
                {
                    //Add it to the waypoints list later to be used on the googleDirection API
                    //Formatted by Comma separator for latitude,longitude
                    _waypoints.Add($"{position.Latitude}%2C{position.Longitude}");

                    //Set pin on map
                    #region SetPin
                    var pin = new Pin()
                    {
                        Position = position,
                        Label    = $"{_invoiceSQLite[i].InvoiceNumber}",
                        //set tag so i can reference it when a pin is clicked
                        Tag  = _invoiceSQLite[i].InvoiceID,
                        Icon = BitmapDescriptorFactory.FromBundle(_invoiceSQLite[i].InvoiceType),
                    };
                    pin.Address = "Click for Details";
                    _pins.Add(pin);

                    map.SelectedPinChanged += Map_SelectedPinChanged;
                    map.InfoWindowClicked  += Map_InfoWindowClicked;
                    map.Pins.Add(pin);
                    #endregion

                    _invoices.Add(_storageInvoice[i]);
                }
            }
            return(true);
        }