コード例 #1
0
def geocode(city=None):
    """
    Consider writing docstrings in the Google style:
        https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings

    Where possible, add type annotations as well. For example:
        https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html

    Args:
        city(str): String representation of the city name to geocode

    Returns:
        geopy.location.Location: Location object or None

    Raises:
        RuntimeError: When geocding fails
    """

    try:
        geolocator = Photon(user_agent="LazyTimezoneSearch 0.1")
        location = geolocator.geocode(city, exactly_one=True)
    except Exception as err:  # pylint: disable=broad-except
        raise RuntimeError(f"Unable to geocode: '{err}'")

    return location
コード例 #2
0
def calculate_distance_view(request):
    # initial values
    distance = None
    destination = None

    geolocator = Photon(user_agent='distance', timeout=10)
    form = MeasurementModelForm(request.POST or None)

    obj = get_object_or_404(Measurement, id=1)
    ip_ = get_ip_address(request)
    ip = '46.216.43.208'
    lat, lon = get_geo(ip)  # In production app will use 'ip_'
    location = geolocator.geocode(ip)

    # location coordinates
    l_lat = lat
    l_lon = lon
    pointA = (l_lat, l_lon)

    if form.is_valid():
        instance = form.save(commit=False)
        destination_ = form.cleaned_data.get('destination')
        destination = geolocator.geocode(destination_)

        # destination coordinates
        d_lat = destination.latitude
        d_lon = destination.longitude
        pointB = (d_lat, d_lon)

        # distance calculation
        distance = round(geodesic(pointA, pointB).km, 2)

        instance.location = location
        instance.distance = distance
        instance.save()

    context = {
        'distance': distance,
        'destination': destination,
        'form': form,
    }

    return destination
コード例 #3
0
ファイル: main.py プロジェクト: progressify/Geolocator
def main():
    geolocator = Photon()

    wb = load_workbook(filename='File.xlsx')
    sheets = wb.sheetnames
    sheet = wb[sheets[0]]  # selecting always the first sheet
    row_count = sheet.max_row
    column_count = sheet.max_column
    for i in range(2, row_count):
        if i % 10 == 0:
            wb.save("File.xlsx")

        address = sheet.cell(row=i, column=ADDRESS_COLUMN).value
        cap = sheet.cell(row=i, column=CAP_COLUMN).value
        loc = sheet.cell(row=i, column=LOC_COLUMN).value

        if address and cap and loc:
            full_address = f'{address} {loc} {cap} ITALIA'
            print(i, full_address)
            try:
                location = geolocator.geocode(full_address, timeout=10)
                sheet.cell(row=i, column=LAT_COLUMN).value = location.latitude
                sheet.cell(row=i, column=LON_COLUMN).value = location.longitude
                sheet.cell(row=i, column=PRECISION_COLUMN).value = ''
            except:
                try:
                    location = geolocator.geocode(f'{cap} {loc} ITALIA',
                                                  timeout=10)
                    sheet.cell(row=i,
                               column=LAT_COLUMN).value = location.latitude
                    sheet.cell(row=i,
                               column=LON_COLUMN).value = location.longitude
                    sheet.cell(row=i, column=PRECISION_COLUMN).value = '0'
                except:
                    sheet.cell(row=i, column=LAT_COLUMN).value = ''
                    sheet.cell(row=i, column=LON_COLUMN).value = ''
                    sheet.cell(row=i, column=PRECISION_COLUMN).value = '-1'

            print(
                f'({sheet.cell(row=i, column=LAT_COLUMN).value}, {sheet.cell(row=i, column=LON_COLUMN).value})'
            )

    wb.save("File.xlsx")
コード例 #4
0
def attractions(city, country):
    # checking coordinates of given city
    geolocator = Photon(user_agent="MobileTravel")
    location = geolocator.geocode(f'{city} {country}')
    lat = location.latitude
    lon = location.longitude
    maxLat = lat+0.05
    maxLot = lon+0.05
    apiKEY = '5ae2e3f221c38a28845f05b6b5db6f06770f4edf010d553f8a337b76'
    url = f"https://api.opentripmap.com/0.1/en/places/bbox?lon_min={lon}&lat_min={lat}&lon_max={maxLot}&lat_max={maxLat}&format=geojson&apikey={apiKEY}"
    response = requests.request("GET", url)
    return response.content
コード例 #5
0
 def handle(self, *args, **options):
     try:
         geo_locator = Photon()
         customers = Customer.objects.all()
         a = 0
         for customer in customers:
             location = geo_locator.geocode(customer.city, timeout=15)
             if location:
                 customer.latitude = location.latitude
                 customer.longitude = location.longitude
                 print(customer.id)
                 customer.save()
             else:
                 a += 1
                 print(a)
         self.stdout.write(
             self.style.SUCCESS('Successfully filled addresses'))
     except CommandError:
         raise
コード例 #6
0
ファイル: views.py プロジェクト: Elmandouh1/GeoDjango-App
def calcDistanceView(request):
    distance = None
    destination = None
    form = MeasurementForm(request.POST or None)
    geolocator = Photon(user_agent="measurements")

    # Location Coordinates
    g = geocoder.ip('me')
    lat = g.latlng[0]
    lon = g.latlng[1]
    location = geolocator.reverse(f"{lat}, {lon}")
    pointA = [lat, lon]

    # Initial Folium Map
    m = folium.Map(width='100%',
                   height='100%',
                   location=get_center_coordinates(lat, lon))
    # Location Marker
    folium.Marker([lat, lon],
                  tooltip='Click here for more',
                  popup=location,
                  icon=folium.Icon(color='blue', icon='home')).add_to(m)

    if form.is_valid():
        instance = form.save(commit=False)

        # destination coordinates
        destination_ = form.cleaned_data.get('destination')
        destination = geolocator.geocode(destination_)
        d_lat = destination.latitude
        d_lon = destination.longitude
        pointB = (d_lat, d_lon)

        # calc distance
        distance = round(geodesic(pointA, pointB).km, 2)  # calc the distance

        # Destination Marker
        m = folium.Map(width='100%',
                       height='100%',
                       location=get_center_coordinates(lat, lon, d_lat, d_lon),
                       zoom_start=get_zoom(distance))
        # Location Marker
        folium.Marker([lat, lon],
                      tooltip='Click here for more',
                      popup=get_center_coordinates(lat, lon),
                      icon=folium.Icon(color='blue', icon='home')).add_to(m)
        folium.Marker([d_lat, d_lon],
                      tooltip='Click here for more',
                      popup=destination,
                      icon=folium.Icon(color='red', icon='cloud')).add_to(m)

        # Draw a line between location and destination
        line = folium.PolyLine(locations=[pointA, pointB],
                               weight=3,
                               color='blue')
        m.add_child(line)  # Append the Line to the Map

        # Location
        instance.location = location
        # Distance
        instance.distance = distance
        instance.save()
    # Map Representation
    m = m._repr_html_()
    context = {
        'distance': distance,
        'destination': destination,
        'form': form,
        'map': m,
    }
    return render(request, 'measurements/main.html', context)
コード例 #7
0
    def extract_location(self, country, state, city, street, postal_code):
        """
        Creates all possible location-related items with the available information.

        Args:
            register -> WHOISregister object with all the information to extract
        """
        # Doesn't even try to create a location entity if there's not at least a country
        if country:

            area = None
            area_code = None

            try:
                country_code = pycountry.countries.lookup(
                    country.decode("utf-8")).alpha_2.decode("utf-8")
            except:
                country_code = None

            # Geolocation
            geolocator = Geocoder(user_agent="Maltego", timeout=2)

            try:
                if street:
                    search += street + ", "

                if city:
                    search += country + ", "

                search += country

                location = geolocator.geocode(search, exactly_one=True)

            except:
                # Tries it again after sleeping a couple of seconds
                try:
                    sleep(2)
                    search = ""

                    if street:
                        search += street + ", "

                    if city:
                        search += country + ", "

                    search += country

                    location = geolocator.geocode(search, exactly_one=True)

                except:
                    location = None

            if country_code:
                choices = pycountry.subdivisions.get(country_code=country_code)
            else:
                choices = pycountry.subdivisions

            # State or province
            if state:
                found = process.extractOne(state, choices)

                # Discards it if the score is lower than 50
                if found and found[1] > 50:
                    state = found[0]

                    area = state.name.decode("utf-8")
                    area_code = state.code.decode("utf-8")

                    if not country_code:
                        # Gets the country code from the state info
                        country_code = state.country_code.decode("utf-8")
            else:
                area = None
                area_code = None

            # Sanitizes all values before creating the XML
            country = country.decode("utf-8")
            street = street.decode("utf-8") if street else None
            city = city.decode("utf-8") if city else None

            return ents.Location(
                name=(city + ", " + country) if city else country,
                city=city,
                country=country,
                streetaddress=street,
                area=area,
                areacode=area_code,
                countrycode=country_code,
                longitude=location.longitude if location else 0,
                latitude=location.latitude if location else 0)

        return None
コード例 #8
0
def updateRow(row):
    global rId
    vybeRow = {}
    global countriesDict, iterationStatusCode, errorRecordDict
    row["category"] = None
    row['cuisine'] = stripAndSplit(row['cuisine'])
    row['phone'] = stripAndSplit(row['phone'])
    row['__v'] = 0
    row['rating'] = None
    row['tags'] = None
    row['videoLink'] = None
    row['reviewCount'] = None
    row['isClaimed'] = None
    row['faq'] = None
    # row['category'] = None
    row['securityDocumentUrl'] = None
    row['securityDocumentName'] = None
    row['socialMediaHandles'] = {
        "facebook": None,
        "instagram": None,
        "twitter": None,
        "snapchat": None,
        "pinterest": None
    }
    row['hoursType'] = "REGULAR"
    row['isOpenNow'] = True
    row['specialHours'] = [{
        "date": None,
        "start": None,
        "end": None,
        "isOvernight": None
    }]
    row['attributes'] = {
        "businessParking": {
            "garage": None,
            "street": None
        },
        "genderNeutralRestrooms": None,
        "openToAll": None,
        "restaurantsTakeOut": None,
        "wheelChairAccessible": None
    }

    postRestaurantName = row['name']
    postAddress = row['oldAddress']
    postCity = row["area"].split(",")[-1]
    url = "https://qozddvvl55.execute-api.us-east-1.amazonaws.com/Prod/vybe/"
    payload = {"name": postRestaurantName, "address": postAddress}
    headers = {'Content-Type': 'text/plain'}

    for i in range(5):
        if i == 1:
            payload['address'] = postCity
        elif i == 2:
            payload['address'] = postAddress.split(",")[-1]
        elif i == 3:
            params = {
                'name': postRestaurantName,
                "city": postCity,
                'address1': postAddress,
                'state': stateName,
                'country': "US"
            }

            yelpReq = requests.get(yelpUrl, params=params, headers=head)
            try:
                address = " ".join(yelpReq.json()["businesses"][0]["location"]
                                   ["display_address"])
                payload['address'] = address
            except:
                root_logger.warning(
                    f"Yelp can't find the address for {payload['name']}")
                continue
        elif i == 4:
            try:
                geolocator = Photon(user_agent="My-app")
                location = geolocator.geocode(postAddress)
                if location is not None:
                    payload['address'] = location.address
                else:
                    root_logger.warning(
                        f"Photon could not find address for {payload['name']}")
            except Exception as e:
                root_logger.warning(f"Photon failed for {payload['name']}")
                root_logger.exception(e)
        response = requests.request("POST",
                                    url,
                                    headers=headers,
                                    data=json.dumps(payload))
        statusCode = response.status_code
        root_logger.info(
            f"{statusCode} - ({postRestaurantName}) - ({payload['address']}) iteration ({i})"
        )
        if statusCode == 200:
            iterationStatusCode[str(i)] += 1
        if statusCode == 200 or statusCode == 502:
            break

    if statusCode == 200:
        res = response.json().get('message')
        restaurantId = 'RestId' + datetime.now().strftime("%d%m%y%H%M") + \
            str(rId).zfill(3)
        # increase this if want to use threading to execute more than 1000 records at a time
        rId = (rId + 1) % 1000
        hour = parseTime(res.get('timings'))
        website = res.get('website')
        address = parseAddress(res.get('address_broken'))
        coordinates = {
            "coordinates": [
                res.get('coordinates').get("longitude"),
                res.get('coordinates').get("latitude")
            ],
            "type":
            "Point"
        }
        newAddress = res.get('address')
        vybe = parseVybe(res.get('vybe'))

        if vybe:
            minTimeSpent = res.get('timeSpent')[0] if res.get(
                'timeSpent') else None
            maxTimeSpent = res.get('timeSpent')[1] if res.get(
                'timeSpent') else None
            vybeRow.update({
                "restaurantId": restaurantId,
                'vybe': vybe,
                'minTimeSpent': minTimeSpent,
                'maxTimeSpent': maxTimeSpent
            })
            countriesVybeDict.append(vybeRow)
        else:
            root_logger.warning("{} No VybeData ( {} ) ( {} )".format(
                statusCode, postRestaurantName, postAddress))

        row.update({
            "restaurantId": restaurantId,
            "location": coordinates,
            "newAddress": newAddress,
            "hours": hour,
            "website": website,
            "address": address
        })

        countriesDict.append(row)
        #print(countriesDict)

    else:
        hour = None
        website = None
        address = None
        newAddress = None
        address = None
        row.update({
            "newAddress": newAddress,
            "hours": hour,
            "website": website,
            "address": address
        })
        errorRecordDict.append(row)
        root_logger.info(
            "{} Entered restaurant with name ( {} ) and address( {} ) into error file"
            .format(statusCode, postRestaurantName, postAddress))
    return statusCode
コード例 #9
0
    def extract_location(self, location_str, country_code):
        """
        Creates a location with the information

        Args:
            location_str -> String with the aproximate location (country, city...)
            country_code -> Code to extract more information, if it wasn't deduced
                with only the location string
        """
        city = None
        country = None
        area = None
        area_name = None
        area_code = None

        if country_code:
            country = pycountry.countries.lookup(country_code)
            if country:
                country = country.name

        if location_str:
            # Uses the location string to create a more precise location

            # Geolocation
            geolocator = Geocoder(user_agent="Maltego", timeout=2)

            try:
                location = geolocator.geocode(location_str, exactly_one=True)

            except:
                # Tries it again after sleeping a couple of seconds
                try:
                    sleep(2)
                    location = geolocator.geocode(location_str,
                                                  exactly_one=True)

                except:
                    location = None

            # If the returned value isn't a country or a continent
            loc_properties = location.raw["properties"]
            if "osm_value" in loc_properties \
                and loc_properties ["osm_value"].lower () != "continent" \
                and loc_properties ["osm_value"].lower () != "country":

                if "name" in loc_properties:
                    area = loc_properties["name"]

                if "country" in loc_properties:
                    # Overrides the country extracted with the country code (if any)
                    country = loc_properties["country"]

                if loc_properties ["osm_value"].lower () == "city" \
                    and "name" in loc_properties:

                    city = loc_properties["name"]

        # State or province
        if area and country_code:
            choices = pycountry.subdivisions.get(country_code=country_code)
            found = process.extractOne(area, choices)

            # Discards it if the score is lower than 50
            if found and found[1] > 50:
                state = found[0]

                area_name = state.name.decode("utf-8")
                area_code = state.code.decode("utf-8")

                if not country_code:
                    # Gets the country code from the state info
                    country_code = state.country_code.decode("utf-8")

        # Sanitizes all values before creating the XML
        country = country.decode("utf-8") if country else None
        city = city.decode("utf-8") if city else None

        return ents.Location(name=(city + ", " + country) if city else country,
                             city=city,
                             country=country,
                             area=area,
                             areacode=area_code,
                             countrycode=country_code,
                             longitude=location.longitude if location else 0,
                             latitude=location.latitude if location else 0)
コード例 #10
0
def get_geodata(location):
    geolocator = Photon(user_agent='measurements')
    geodata = geolocator.geocode(location)
    return geodata
コード例 #11
0
import csv
from geopy.geocoders import Photon

geolocator = Photon()

hdr = {}

with open('public/data/master.csv', 'rb') as csvinput:
    with open('public/data/master_latlong.csv', 'w') as csvoutput:
        writer = csv.writer(csvoutput, lineterminator='\n')
        reader = csv.reader(csvinput)

        all = []
        row = reader.next()
        row.append('latitude')
        row.append('longitude')
        all.append(row)

        for row in reader:
            try:
                location = geolocator.geocode(row[2], timeout=10)
                print location.latitude
                print location.longitude
                row.append(location.latitude)
                row.append(location.longitude)
                all.append(row)
            except IndexError:
                print "INDEXRROR HAPPENED"
                continue

        writer.writerows(all)
コード例 #12
0
def calculate_distance_view(request):

    distance=None
    destination=None
    obj=get_object_or_404(Measurements,id=1)
    form=MeasurementModelForm(request.POST or None)
    ##user_agent = name of app
    geolocator=Photon(user_agent="measurements")

    ip_=get_ip_address(request)
    print(ip_)
    ip="72.14.207.99"
    country,city,lat,lon =get_geo(ip)
    #print("Location country:",country)
    #print("Location city:",city)
    #print("Location latitude and longitude:",lat,lon)

    location=geolocator.geocode(city)
    #print("###",location)

    #location coordinates
    l_lat=lat
    l_lon=lon
    pointA=(l_lat,l_lon)

    #initial folium map
    m=folium.Map(width=1100,height=400,location=get_center_coordinates(l_lat,l_lon),zoom_start=8)

    #location marker
    folium.Marker([l_lat,l_lon],tooltip="Click here for more",popup=city["city"],
                  icon=folium.Icon(color="purple")).add_to(m)

    if form.is_valid():
        instance=form.save(commit=False)
        destination_=form.cleaned_data.get("destination")
        destination=geolocator.geocode(destination_)
        print(destination)
        #destination coordinates
        d_lat=destination.latitude
        d_lon=destination.longitude

        pointB=(d_lat,d_lon)
        #distance calculation
        distance=round(geodesic(pointA,pointB).km,2)

        #folium map modification
        m=folium.Map(width=800,height=400,location=get_center_coordinates(l_lat,l_lon,d_lat,d_lon),
                     zoom_start=get_zoom(distance))

        #location marker
        folium.Marker([l_lat,l_lon],tooltip="Click here for more",popup=city["city"],
                  icon=folium.Icon(color="purple")).add_to(m)
        #destination marker
        folium.Marker([d_lat,d_lon],tooltip="Click here for more",popup=destination,
                  icon=folium.Icon(color="red",icon="cloud")).add_to(m)
        #draw the line between the location and destination
        line=folium.PolyLine(locations=[pointA,pointB],weight=8,color="blue")
        m.add_child(line)

        instance.location=location
        instance.distance=distance
        instance.save()
    else:
        pass
    #converting into html which is later used by using {{map}safe}} in main.html
    m=m._repr_html_()


    context={
        'distance':distance,
        'destination':destination,
        'form':form,
        'map':m,
        }

    return render(request,"measurements/main.html",context)
コード例 #13
0
def calculate_distance_view(request):
    # device=False;
    obj = get_object_or_404(Measurement, id=1)
    form = MeasurementModelForm(request.POST or None)
    geolocator = Photon(user_agent='measurements')

    ip = '103.87.141.65'
    country, city, lat, lon = get_geo(ip)
    print('location country', country)
    print('location city', city)

    # print('location lat, lon', lat, lon)

    # just to see the location
    location = geolocator.geocode(city)
    print('### location:', location)

    #Location coordinates
    l_lat = lat
    l_lon = lon
    pointA = (l_lat, l_lon)

    # Inital Folium map
    m = folium.Map(width=8000,
                   height=500,
                   location=get_center_coordinates(l_lat, l_lon),
                   zoom_start=8)

    # Location marker
    folium.Marker([l_lat, l_lon],
                  tooltip='click here for more',
                  popup=city['city'],
                  icon=folium.Icon(color='red')).add_to(m)

    if form.is_valid():
        instance = form.save(commit=False)
        destination_ = form.cleaned_data.get('destination')
        destination = geolocator.geocode(destination_)
        print('destination', destination)

        # Destination coordinates
        d_lat = destination.latitude
        d_lon = destination.longitude
        pointB = (d_lat, d_lon)

        # Distance calculation
        distance = round(geodesic(pointA, pointB).km, 2)

        # Inital Folium map
        m = folium.Map(width=8000,
                       height=500,
                       location=get_center_coordinates(l_lat, l_lon, d_lat,
                                                       d_lon),
                       zoom_start=get_zoom(distance))

        # Location marker
        folium.Marker([l_lat, l_lon],
                      tooltip='click here for more',
                      popup=city['city'],
                      icon=folium.Icon(color='red')).add_to(m)
        # Destination marker
        # if(device):
        folium.Marker([d_lat, d_lon],
                      tooltip='click here for more',
                      popup=destination,
                      icon=folium.Icon(color='green')).add_to(m)
        # else:
        #            folium.Marker([d_lat, d_lon], tooltip='click here for more', popup=destination,
        #             icon=folium.Icon(color='red')).add_to(m)

        # Draw line between destination and location
        #line = folium.PolyLine(locations=[pointA,pointB], weight = 2, color= 'blue')
        #m.add_child(line)

        instance.location = location
        instance.distance = distance
        instance.save()

    m = m._repr_html_()

    context = {
        'distance': obj,
        'form': form,
        'map': m,
    }

    return render(request, 'main.html', context)
コード例 #14
0
# from geopy.geocoders import Yandex
# from geopy.geocoders import DataBC
# from geopy.geocoders import Nominatim
from geopy.geocoders import Photon

# geolocator = GoogleV3(scheme='http')
# geolocator = Yandex(lang='en', scheme='http')
# geolocator = DataBC(scheme='http')
# geolocator = Nominatim(scheme='http', user_agent='my-application')
geolocator = Photon(scheme='http')


address1 = '3995 23rd St, San Francisco, CA 94114, USA'
address2 = '3730 Cambie St, Vancouver, BC V5Z2X5, Canada'

location = geolocator.geocode(address1)

print(type(location))
# <class 'geopy.location.Location'>
print(dir(location))
# [... 'address', 'altitude', 'latitude', 'longitude', 'point', 'raw']
print(location)
# 3995 23rd St, San Francisco, CA 94114, USA
print(location.address)
# 3995 23rd St, San Francisco, CA 94114, USA
print(location.altitude)
# 0.0
print((location.latitude, location.longitude))
# (37.7529648, -122.4317141)
print(location.point)
# 37 45m 10.6733s N, 122 25m 54.1708s W
コード例 #15
0
ファイル: views.py プロジェクト: LukaszRemkowicz/GeoCastle
def calculate_distance_view(request):
    # initial values
    nominatim = Nominatim()

    global castle_ide
    #areaId = nominatim.query('poland').areaId()

    overpass = Overpass()
    api = Api()
    name = None
    review = None
    state = None

    country = nominatim.query('germany')

    locator = Photon()  # (user_agent='martin_jr8')
    areaId = country.areaId()
    names_query = country.toJSON()
    country_details = names_query[0]
    country_coor_lat = country_details["lat"]
    country_coor_lon = country_details["lon"]

    # castles location query
    castle_query = overpassQueryBuilder(area=areaId,
                                        elementType='node',
                                        selector='castle_type',
                                        out='body')
    castle_objects = overpass.query(castle_query)
    castle_list = castle_objects.elements()

    # castle_infos = []
    # for castle in castle_list:
    #     castle_infos.append(castle.tags())

    # initail folium map
    m = folium.Map(location=[country_coor_lat, country_coor_lon], zoom_start=6)

    for castle_loc in castle_list:
        info_dict = castle_loc.tags()
        castle_id = castle_loc.id()
        castle_name = info_dict.get('name')
        if castle_name == None:
            continue
        else:
            folium.Marker(
                [castle_loc.lat(), castle_loc.lon()],
                tooltip=castle_name,
                popup=folium.Popup(popup_box(info_dict.get('name'), castle_id),
                                   max_width=500),
                icon=folium.Icon(color='purple',
                                 icon='fort-awesome',
                                 prefix='fa')).add_to(m)

    if request.user.is_authenticated:
        user = Profile.objects.get(user=request.user)
        loc = user.location
        location = locator.geocode(loc)
        l_lat = location.latitude
        l_lon = location.longitude
        loc_point = (l_lat, l_lon)

        folium.Marker([l_lat, l_lon],
                      tooltip='Your Location',
                      popup=location,
                      icon=folium.Icon(color='blue', icon='home',
                                       prefix='fa')).add_to(m)

    if request.method == 'GET' and request.is_ajax():
        castle_ide = request.GET.get('castle_id')
        castle_data = api.query(f'node/{castle_ide}')
        castle_details = castle_data.tags()

        # if request.user.is_authenticated and user.location != None:
        #     castle_lat = castle_data.lat()
        #     castle_lon = castle_data.lon()
        #     castle_point = (castle_lat, castle_lon)
        #     distance = round(geodesic(loc_point, castle_point).km, 2)
        #     castle_details["distance"] = distance

        # line = folium.PolyLine(locations=[loc_point, castle_point], weight=2, color='blue')
        # m.add_child(line)
        # m = m._repr_html_()

        return HttpResponse(json.dumps(castle_details),
                            content_type="application/json")

    if request.user.is_authenticated and request.method == 'POST' and request.is_ajax(
    ):
        castleName = request.POST.get('castleName')
        review = request.POST.get('review')
        state = request.POST.get('state')
        user = request.user
        ide = castle_ide
        form = LocationsModelForm()
        form.save(user, castleName, review, state, ide)

        folium.Marker([52.352, 6.22],
                      tooltip='Your Location',
                      popup=location,
                      icon=folium.Icon(color='green', icon='home',
                                       prefix='fa')).add_to(m)
        messages.info(request, 'success. Review saved')

        # m = m._repr_html_()

        # return redirect('/')

        # return HttpResponseRedirect('measurements/main.html')

        # return render(request, 'measurements/main.html', {'map': m})

        # return render(request, 'measurements/main.html')

        # return HttpResponse(request)

    m = m._repr_html_()

    context = {
        # 'name': name,
        # 'review': review,
        # 'state': state,
        # 'map': m,
        # 'castles': country_coor_lat,
        # 'ops' : border_objects
        # 'name': requested_id
    }

    return render(request, 'measurements/main.html', {'map': m})
コード例 #16
0
def calculate_distance_view(request):
    #initial distance
    distance = None
    destination = None
    obj = get_object_or_404(Measurement, id=1)
    form = MeasurementModelForm(request.POST or None)
    geolocator = Photon(user_agent="measurements")

    ip_ = get_ip_address(request)
    print(ip_)

    ip = "72.14.207.99"
    country, city, lat, lon = get_geo(ip)

    location = geolocator.geocode(city)

    l_lat = lat
    l_lon = lon
    pointA = (l_lat, l_lon)

    #initial folium map
    m = folium.Map(width=750,
                   height=500,
                   location=get_center_coodinates(l_lat, l_lon),
                   zoom_start=8)
    #location maker
    folium.Marker([l_lat, l_lon],
                  tooltip="Click Here For More",
                  popup=city['city'],
                  icon=folium.Icon(color='purple')).add_to(m)

    if form.is_valid():
        instance = form.save(commit=False)
        destination_ = form.cleaned_data.get('destination')
        destination = geolocator.geocode(destination_)

        #destination cordinate
        d_lat = destination.latitude
        d_lon = destination.longitude

        pointB = (d_lat, d_lon)

        #distance calculations
        distance = round(geodesic(pointA, pointB).km, 2)

        #folium map modification
        m = folium.Map(width=750,
                       height=500,
                       location=get_center_coodinates(l_lat, l_lon, d_lat,
                                                      d_lon),
                       zoom_start=get_zoom(distance))
        #location maker
        folium.Marker([l_lat, l_lon],
                      tooltip="Click Here For More",
                      popup=city['city'],
                      icon=folium.Icon(color='purple')).add_to(m)
        #destination maker
        folium.Marker([d_lat, d_lon],
                      tooltip="Click Here For More",
                      popup=destination,
                      icon=folium.Icon(color='red', icon='cloud')).add_to(m)

        #Draw the line between location and destination
        line = folium.PolyLine(locations=[pointA, pointB],
                               weight=2,
                               color='blue')
        m.add_child(line)

        instance.location = location
        instance.distance = distance
        instance.save()
    m = m._repr_html_()
    context = {
        'distance': distance,
        'destination': destination,
        'form': form,
        'map': m,
    }
    return render(request, 'measurements/main.html', context)
コード例 #17
0
def create_map(year, locations):
    """
    (int, dict) -> int
    Create a map of films for the specific year and save it to MoviesMap.html
        locations: dict of {location: number of films}
    """
    import folium
    from geopy.geocoders import Photon
    from geopy.exc import GeocoderTimedOut
    import math

    def get_color(num):
        """
        (int) -> str
        Return a color depending on num
        >>> get_color(1)
        '#05fa20
        >>> get_color(1000)
        '#9e6120
        >>> get_color(10000)
        '#ff2020'
        """
        color = '#'
        red = int(num**(1 / 2) * 5)
        if red > 255:
            color += 'ff'
            red = 255
        else:
            color += '0' + hex(red)[2:] if red < 16 else hex(red)[2:]
        green = 255 - red
        color += '20' if green < 16 else hex(green)[2:]
        color += '20'
        return color

    geolocator = Photon()
    fmap = folium.Map(location=[49, 24], zoom_start=5)
    fg_films = folium.FeatureGroup(name='Фільми на %i рік' % year)
    fg_pp = folium.FeatureGroup(name='Населення країн')
    fg_pp.add_child(
        folium.GeoJson(
            data=open('world.json', 'r', encoding='utf-8-sig').read(),
            tooltip=folium.features.GeoJsonTooltip(fields=['NAME', 'POP2005'],
                                                   aliases=['', '']),
            style_function=lambda x: {
                'opacity':
                0,
                'fillColor':
                '#f0f0f0'
                if x['properties']['POP2005'] < 10000000 else '#b0b0b0'
                if x['properties']['POP2005'] < 50000000 else '#808080'
                if x['properties']['POP2005'] < 100000000 else '#404040'
                if x['properties']['POP2005'] < 500000000 else '#101010'
            }))
    i = 0
    errors = 0
    total = len(locations.keys())
    bar = 20
    print("Generating map...")
    for address in locations.keys():
        i += 1
        percent = i / total
        print('\r[' + '▋' * int(percent * bar) + ' ' *
              (bar - int(percent * bar)) + ']' + str(int(percent * 100)) + '%',
              end='')
        try:
            location = geolocator.geocode(address)
            if location is None:
                location = geolocator.geocode(address[address.find(',') + 2:])
            if location is not None:
                lat = location.latitude
                lon = location.longitude
                color = get_color(locations[address])
                fg_films.add_child(
                    folium.CircleMarker(
                        location=[lat, lon],
                        radius=4 + int(math.sqrt(locations[address]) / 3),
                        popup=address +
                        ': \n%i фільм(ів)' % locations[address],
                        color=color,
                        fill_color=color,
                        fill_opacity=0.5,
                        stroke=0))
            else:
                errors += 1
        except GeocoderTimedOut:
            errors += 1
    print('\n %i found, %i errors' % (i - errors, errors))
    fmap.add_tile_layer(name='CartoDB', tiles='CartoDB')
    fmap.add_child(fg_pp)
    fmap.add_child(fg_films)
    fmap.add_child(folium.LayerControl())
    fmap.save('MoviesMap.html')

    return 0
コード例 #18
0
def calculate_distance_view(request):
    distance = None
    destination = None
    obj = get_object_or_404(Measurement, id=1)
    form = MeasurementModelForm(request.POST or None)
    geolocator = Photon(user_agent='projectapp')

    ip = '103.98.78.198'
    country, city, lat, lon = get_geo(ip)
    #print('location country',country)
    #print('location city',city)
    #print('location lat,lon',lat,lon)

    location = geolocator.geocode(city)
    # print('###', location)

    # location coordinates

    l_lat = lat
    l_lon = lon
    pointA = (l_lat, l_lon)

    # initial folium map
    m = folium.Map(width=1120,
                   height=640,
                   location=get_center_coordinates(l_lat, l_lon),
                   zoom_start=8)

    # location marker

    folium.Marker([l_lat, l_lon],
                  tooltip='click here for more',
                  popup=city['city'],
                  icon=folium.Icon(color='red')).add_to(m)

    if form.is_valid():
        instance = form.save(commit=False)
        destination_ = form.cleaned_data.get('destination')
        destination = geolocator.geocode(destination_)
        # print(destination)
        d_lat = (destination.latitude)
        d_lon = (destination.longitude)

        pointB = (d_lat, d_lon)

        distance = round(geodesic(pointA, pointB).km, 2)

        # folium map modification

        m = folium.Map(width=1000,
                       height=600,
                       location=get_center_coordinates(l_lat, l_lon, d_lat,
                                                       d_lon),
                       zoom_start=get_zoom(distance))

        # location marker

        folium.Marker([l_lat, l_lon],
                      tooltip='click here for more',
                      popup=city['city'],
                      icon=folium.Icon(color='red')).add_to(m)

        # destination marker

        folium.Marker([d_lat, d_lon],
                      tooltip='click here for more',
                      popup=destination,
                      icon=folium.Icon(color='blue', icon='cloud')).add_to(m)

        # line between location and destination
        line = folium.PolyLine(locations=[pointA, pointB],
                               weight=2,
                               color='blue')
        m.add_child(line)

        instance.location = location
        instance.distance = distance
        instance.save()

    m = m._repr_html_()

    context = {
        'distance': distance,
        'destination': destination,
        'form': form,
        'map': m,
    }

    return render(request, 'measurements/main.html', context)
コード例 #19
0
def calculate_distance_view(request):
    # initial values
    distance = None
    destination = None

    # obj = get_object_or_404(Measurement, id=1)
    form = MeasurementModelForm(request.POST or None)
    geolocator = Photon(user_agent="measurements")

    ip_ = get_ip_address(request)
    print(ip_)
    ip = '14.201.145.52'
    country, city, lat, lon = get_geo(ip)
    # print('location country', country)
    # print('location city', city)
    # print('location lat, lon', lat, lon)

    location = geolocator.geocode(city)
    # print('###', location)

    # location coordinates
    l_lat = lat
    l_lon = lon
    pointA = (l_lat, l_lon)

    # initial folium map
    m = folium.Map(width=800,
                   height=500,
                   location=get_center_coordinates(l_lat, l_lon),
                   zoom_start=8)
    # location marker
    folium.Marker([l_lat, l_lon],
                  tooltip='click here for more',
                  popup=city['city'],
                  icon=folium.Icon(color='purple')).add_to(m)

    if form.is_valid():
        instance = form.save(commit=False)
        destination_ = form.cleaned_data.get('destination')
        destination = geolocator.geocode(destination_)
        # print(destination)
        # print(destination.latitude)
        # print(destination.longitude)

        # destination coordinates
        d_lat = destination.latitude
        d_lon = destination.longitude

        pointB = (d_lat, d_lon)

        # distance calculation
        distance = round(geodesic(pointA, pointB).km, 2)

        # folium map modification
        m = folium.Map(width=800,
                       height=500,
                       location=get_center_coordinates(l_lat, l_lon, d_lat,
                                                       d_lon),
                       zoom_start=get_zoom(distance))
        # location marker
        folium.Marker([l_lat, l_lon],
                      tooltip='click here for more',
                      popup=city['city'],
                      icon=folium.Icon(color='purple')).add_to(m)
        # destination marker
        folium.Marker([d_lat, d_lon],
                      tooltip='click here for more',
                      popup=destination,
                      icon=folium.Icon(color='red', icon='cloud')).add_to(m)

        # draw the line between location and destination
        line = folium.PolyLine(locations=[pointA, pointB],
                               weight=5,
                               color='blue')
        # adding the line to the map
        m.add_child(line)

        instance.location = location
        instance.distance = distance
        # instance.location = 'San Francisco'
        # instance.distance = 5000.00
        instance.save()

    # To get an HTML representation of the folium map
    m = m._repr_html_()

    context = {
        'distance': distance,
        'destination': destination,
        'form': form,
        'map': m,
    }

    return render(request, 'measurements/main.html', context)
コード例 #20
0
ファイル: views.py プロジェクト: JaradTryffin/FindCupCake
def frontpage(request):
    start_point = None
    distance = None
    end_point = None
    cost = None
    time = None
    form = MeasurementForm(request.POST or None)
    geolocator = Photon(user_agent='measurements')

    # ip_ = get_ip_address(request)
    # print(ip_)
    # ip = '164.160.36.116'
    # country,city,lat,lon =get_geo(ip)
    # nowLocation = geolocator.geocode(city)
    # now_lat = lat
    # now_lon =lon
    # nowPoint = (now_lat,now_lon)
    m = folium.Map(width=800,
                   height=500,
                   location=get_center_coordinates(-28.579397200000002,
                                                   24.086794125366062),
                   zoom_start=3)
    folium.Marker([-28.579397200000002, 24.086794125366062],
                  tooltip="South Africa",
                  icon=folium.Icon(color='purple')).add_to(m)

    if form.is_valid():

        instance = form.save(commit=False)
        start_point_ = form.cleaned_data.get('start_point')
        start_point = geolocator.geocode(start_point_)
        print(start_point)
        print(start_point.latitude)
        print(start_point.longitude)
        start_lat = start_point.latitude
        start_lon = start_point.longitude
        pointA = (start_lon, start_lat)

        end_point_ = form.cleaned_data.get('end_point')
        end_point = geolocator.geocode(end_point_)
        print(end_point)
        print(end_point.latitude)
        print(end_point.longitude)
        end_lat = end_point.latitude
        end_lon = end_point.longitude
        pointB = (end_lon, end_lat)

        distance = round(geodesic(pointA, pointB).km, 2)
        cost = form.cleaned_data.get('cost')
        time = form.cleaned_data.get('time')

        points = [
            [start_lat, start_lon],
            [end_lat, end_lon],
        ]

        m = folium.Map(location=get_center_coordinates(start_lat, start_lon,
                                                       end_lat, end_lon),
                       zoom_start=get_zoom(distance))
        folium.Marker([start_lat, start_lon],
                      tooltip='click here for more',
                      popup=start_point,
                      icon=folium.Icon(color='purple')).add_to(m)
        folium.Marker([end_lat, end_lon],
                      tooltip='click here for more',
                      popup=end_point,
                      icon=folium.Icon(color='red')).add_to(m)

        line = folium.PolyLine(points, weight=2, color='blue')
        m.add_child(line)
        # (start_lat,start_lon,end_lat,end_lon)

        instance.distance = distance
        instance.cost = instance.distance * instance.price_per_km
        instance.time = instance.distance / instance.price_per_hour
        instance.save()

    m = m._repr_html_()

    info = Measurements.objects.latest('id')

    context = {
        'form': form,
        'm': m,
        'distance': distance,
        'start_point': start_point,
        'end_point': end_point,
        'info': info
    }
    return render(request, 'measurements/index.html', context)