Coder Social home page Coder Social logo

hi-folks / milk-sdk-php Goto Github PK

View Code? Open in Web Editor NEW
7.0 2.0 12.0 391 KB

Milk SDK PHP is a (fluent) open-source PHP library that makes it easy to integrate your PHP application with location services like Geocode, Route, Isoline, Search Places and Address, location data ...

Home Page: https://packagist.org/packages/hi-folks/milk-sdk-php

License: MIT License

PHP 99.48% Makefile 0.52%
php geolocation location-services location-data geocoder-api hacktoberfest hacktoberfest2021

milk-sdk-php's Introduction

Milk SDK PHP

Actions Status GitHub license

Milk SDK PHP

Milk SDK PHP is a (fluent) open-source PHP library that makes it easy to integrate your PHP application with location services like:

Getting Started

Install the SDK

In your PHP project install package via Composer:

composer require hi-folks/milk-sdk-php

Obtain HERE API Key

To use HERE Location Services you will need an API key. The API key is a unique identifier that is used to authenticate API requests associated with your project. There is a official tutorial for retrieving the API Key: https://developer.here.com/tutorials/getting-here-credentials/

Weather API

With Weather API class you can get weather forecasts, observation, or alerts for a specific location.

You can call the following methods to get the corresponding weather information:

  • productObservation(): Get current weather conditions from the eight closest locations to the specified location.
  • productAlerts(): Get forecasted weather alerts for the next 24 hours.
  • productForecast7days(): Get morning, afternoon, evening and night weather forecasts for the next seven days.
  • productForecast7daysSimple(): Get daily weather forecasts for the next seven days.
  • productForecastAstronomy(): Get information on when the sun and moon rise and set, and on the phase of the moon for the next seven days.
  • productForecastHourly(): Get hourly weather forecasts for the next seven days.
  • productNwsAlerts(): Get all active watches and warnings for the US and Canada.

For example, to retrieve weather forecasts in Berlin:

$jsonWeather = Weather::instance()
    ->setAppIdAppCode($hereAppId, $hereAppCode)
    ->productForecast7days()
    ->name("Berlin")
    ->get();
var_dump($jsonWeather->getData());
var_dump($jsonWeather->isError());
var_dump($jsonWeather->getErrorMessage());
var_dump($jsonWeather->getDataAsJsonString());

Routing API (v7)

To retrieve the fastest route by foot

$r = (new RoutingV7())
    ->setApiKey($hereApiKey)
    ->byFoot()
    ->typeFastest()
    ->startingPoint(52.5160, 13.3779)
    ->destination(52.5185, 13.4283)
    ->get();
var_dump($r->getData());
var_dump($r->isError());
var_dump($r->getErrorMessage());
var_dump($r->getDataAsJsonString());

Instead of using get(), you could use getManeuverInstructions() method:

$r = (new RoutingV7())
    ->setApiKey($hereApiKey)
    ->byFoot()
    ->typeFastest()
    ->startingPoint(52.5160, 13.3779)
    ->destination(52.5185, 13.4283)
    ->getManeuverInstructions();

var_dump($r);

Routing API (v8)

To retrieve the fastest route by car

$routingActions = RoutingV8::instance()
    ->setApiKey($hereApiKey)
    ->byCar()
    ->routingModeFast()
    ->startingPoint(52.5160, 13.3779)
    ->destination(52.5185, 13.4283)
    ->returnInstructions()
    ->langIta()
    ->getDefaultActions();

foreach ($routingActions as $key => $action) {
    echo " - ".$action->instruction . PHP_EOL;
}

Geocoding API

In order to retrieve geo-coordinates (latitude, longitude) of a known address or place.

use HiFolks\Milk\Here\RestApi\Geocode;
$hereApiKey = "Your API KEY";
$r = Geocode::instance()
    ->setApiKey($hereApiKey)
    ->country("Italia")
    ->q("Colosseo")
    ->langIta()
    ->get();
var_dump($r->getData());
var_dump($r->isError());
var_dump($r->getErrorMessage());
var_dump($r->getDataAsJsonString());

Reverse Geocoding API

In order to find the nearest address to specific geo-coordinates:

use HiFolks\Milk\Here\RestApi\ReverseGeocode;
$hereApiKey = "Your API KEY";
$r = ReverseGeocode::instance()
    ->setApiKey($hereApiKey)
    ->at(41.88946,12.49239)
    ->limit(5)
    ->lang("en_US")
    ->get();
var_dump($r->getData());
var_dump($r->isError());
var_dump($r->getErrorMessage());
var_dump($r->getDataAsJsonString());

if ($r->isError()) {
    echo "Error: ". $r->getErrorMessage();
} else {
    $items = $r->getData()->items;
    foreach ($items as $key => $item) {
        echo " - " .$item->title.
            " : ( ".$item->position->lat . "," . $item->position->lng .
            " ) , distance:" . $item->distance . " , type: " . $item->resultType . PHP_EOL;
    }
}

Isoline API

use HiFolks\Milk\Here\RestApi\Isoline;
$hereApiKey = "yourapikey";
$isoline = Isoline::instance()
    ->setApiKey($hereApiKey)
    ->originPoint(41.890251, 12.492373)
    ->byFoot()
    ->rangeByTime(600) // 10 minutes
    ->get();

Map Image Api

With MapImage class you can create static image of a map. For the map you can define:

  • center(): the center of the map;
  • addPoi(): add a point in the map;
  • zoom(): set the zoom level;
  • height(): set the height of image (in pixel);
  • width(): set the width of the image (in pixel).
use Hifolks\milk\here\RestApi\MapImage;
$hereApiKey = "yourapikey";
$imageUrl = MapImage::instance($hereApiKey)
    ->center(45.548, 11.54947)
    ->addPoi(45, 12, "ff0000")
    ->addPoi(45.1, 12.1, "00ff00")
    ->addPoi(45.2, 12.2, "0000ff", "", "12", "Test 3")
    ->zoom(12)
    ->height(2048)
    ->width(2048 / 1.4)
    ->getUrl();

You can use also the Geocoding functionality with centerAddress() method.

$image = MapImage::instance($hereApiKey)
    ->centerAddress("Venezia")
    ->zoom(12)
    ->height(2048)
    ->width(intval(2048 / 1.4));
$imageUrl = $image->getUrl();

Discover API

If you need to search an address or a place and you need to validate it and obtain some other information about the location, you can use Discover API endpoint via Discover class.

$address = "Basilica San Marco,  venezia";
// instance the class
$discover = Discover::instance($hereApiKey)
// define the address
    ->q($address)
// define a center point (for example Rome)
    ->at(41.902782, 12.496366)
// define where to limit the search, in this case ITA is the country code for Italy
    ->inCountry("ITA")
    ->get();

If you need to search an address in Italy, you can use inItaly() method:

$address = "Basilica San Marco,  venezia";
$discover = Discover::instance($hereApiKey)
    ->q($address)
    ->inItaly()
    ->get();

Use HERE Data Hub

Configuring XYZ HUB

With this SDK you can consume DataHub (XYZ) API. You have 2 options:

Configure SDK with your own instance of XYZ HUB

Running your own instance of XYZ HUB means that you already have your instance of https://github.com/heremaps/xyz-hub. A tutorial about how to set up XYZ Hub locally (on localhost): https://dev.to/robertobutti/restful-web-service-for-geospatial-data-12ii

Create a .env file. Fill it with:

XYZ_ACCESS_TOKEN=""
XYZ_API_HOSTNAME="http://localhost:8080"

Configure SDK with XYZ HUB Cloud service

Using XYZ HUB Cloud Service means that you are using this host https://xyz.api.here.com.

To use this service you need to sign in as developer on https://developer.here.com/ and create your plan (for example Freemium) and obtain your Access Token.

Once you have your access token, create a .env file. You can start from a sample file (.env.dist):

cp .env.dist .env

Then, you need to fill your XYZ_ACCESS_TOKEN in .env file with your access token.

Quick Examples

In order to use the Milk SDK, you need to:

  • create a PHP file
  • include the autoload.php file
  • declare all imports via use
  • load environment configuration (via Dotenv)
  • get your token
  • get your XYZ Spaces
  • display your result
<?php
// include the autoload.php file
require "./vendor/autoload.php";
// declare all imports via "use"
use HiFolks\Milk\Here\Xyz\Space\XyzSpace;
// set your token
$xyzToken = "your xyz space token";
// Get your XYZ Spaces (XyzResponse class)
$s = XyzSpace::instance($xyzToken)->get();
// display your result
var_dump($s->getData());

Retrieve your XYZ Spaces

To get your XYZ Spaces:

$s = XyzSpace::instance($xyzToken)->get();

To get XYZ Spaces by everybody (not only your own XYZ Spaces):

$s =  XyzSpace::instance($xyzToken)->ownerAll()->get();

Delete Space

To delete a XYZ Space:

$xyzSpaceDeleted = XyzSpace::instance($xyzToken)->delete($spaceId);

Create Space

To create a new XYZ Space:

$xyzSpaceCreated = XyzSpace::instance($xyzToken)->create("My Space", "Description");

Update Space

To update the XYZ Space with space id == $spaceId:

$obj = new \stdClass;
$obj->title = "Edited Title";
$obj->description = "Edited Description";
$retVal = $space->update($spaceId, $obj);

Statistics

The get statistics from XYZ Space:

$statistics =  XyzSpaceStatistics::instance($xyzToken)->spaceId($spaceId)->get();

Features

Iterate features

/** XyzSpaceFeature $xyzSpaceFeature */
$xyzSpaceFeature = new XyzSpaceFeature::instance($xyzToken);
$result = $xyzSpaceFeature->iterate($spaceId)->get();

Retrieve 1 Feature

You need to use feature() method with $featureId and $spaceId

$xyzSpaceFeature = XyzSpaceFeature::instance($xyzToken);
$result = $xyzSpaceFeature->feature($featureId, $spaceId)->get();

Create or Edit 1 Feature

To create or edit a Feature you can use saveOne() method.

$spaceId = "yourspaceid";
$featureId = "yourfeatureid";
$geoJson = new GeoJson();
$properties = [
    "name" => "Berlin",
    "op" => "Put"
];
$geoJson->addPoint(52.5165, 13.37809, $properties, $featureId);
$feature = XyzSpaceFeatureEditor::instance($xyzToken);
$result = $feature->feature($geoJson->get())->saveOne($spaceId, $featureId);
$feature->debug();

Create multiple features from a geojson file

If you have a Geojson File, you can upload it into a space.

$spaceId = "yourspaceid";
$file = "https://data.cityofnewyork.us/api/geospatial/arq3-7z49?method=export&format=GeoJSON";
$response = XyzSpaceFeatureEditor::instance($xyzToken)
    ->addTags(["file"])
    ->geojson($file)
    ->create($spaceId);

Search features by property

To search features by properties you can use addSearchParams to add serach params, in the example below, you are searching features with name property equals "Colosseo".

$spaceId = "yourspaceid";
$xyzSpaceFeature = XyzSpaceFeature::instance($xyzToken)->addSearchParams("p.name", "Colosseo");
$result = $xyzSpaceFeature->search($spaceId)->get();

Search features by proximity

To search feature close to latitude=41.890251 and longitude=12.492373 with a radius less than 1000 meters (close to Colosseum):

$spaceId = "yourspaceid";
$result = XyzSpaceFeature::instance($xyzToken)->spatial($spaceId,  41.890251, 12.492373,  1000)->get();

Useful reference

Data Hub API

HERE Destination Weather API

HERE Rest Routing V8 API

HERE Rest Geocoding API

HERE Rest Reverse Geocoding API

HERE Rest Isoline API

milk-sdk-php's People

Contributors

cgarde89 avatar creativenull avatar iridacea avatar johnaylingdi avatar kamazz avatar kimcheung avatar kjellknapen avatar maal26 avatar roberto-butti avatar soil-droid avatar sonnymilton avatar tchapuis avatar tharindulucky avatar torelafes avatar tspencer244 avatar vrabe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

milk-sdk-php's Issues

Fix for php 7.2 compatibility, array

Fix for php 7.2 compatibility:

Parse error: syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST) in ./src/Utils/GeoJson.php on line 7
Errors parsing ./src/Utils/GeoJson.php

Makefile for unit test, phpstan and phpcs

Create a Make file with some tasks for:

  • launching unit tests:
vendor/bin/phpunit --coverage-text
  • executing phpstan with configuration from phpstan.neon
phpstan analyse
  • executing phpcs for PSR12 standard
phpcs --standard=PSR12 src

phpstan: Create a phpstan.neon configuration file

Create a phpstan.neon configuration file.
In order to execute phpstan always with same parameters set a file in the project directory named phpstan.neon :

parameters:
	level: 6
	fileExtensions:
		- php
	paths:
		- src
	treatPhpDocTypesAsCertain: false

So you are able to execute phpstan analyse (the parameters are loaded from phpstan.neon file)

Add the missing parameter via to Routing API V8

Add the missing parameter via to Routing API V8
API Documentation URL: https://developer.here.com/documentation/routing-api/8.9.1/api-reference-swagger.html

Method: GET

Parameters to implement:

  • via

Value for the parameter:

  • A location defining a via waypoint.

A via waypoint is a location between origin and destination. The route will do a stop at the via waypoint.

Multiple waypoints can also be specified using multiple via parameters like via=...&via=..., in which case the route will traverse these waypoints sequentialy in the order specified in the request.

File: src/Here/RestApi/RoutingV8.php

Extend compatibility for guzzle, phpdotenv, phpunit

Extend compatibility for this library:
"guzzlehttp/guzzle": "^6.3|^7.0",
"vlucas/phpdotenv": "^3.3|^4.0|^5.2"
"phpunit/phpunit": "^7.5.15|^8.4|^9.0"

In this way we could install it with Laravel 8, Laravel 7 and Laravel 6

Avoid duplicate code for adding api key in src/Here/RestApi/* files

In:

  • Geocode.php
  • Isoline.php
  • MapImage.php
  • ReverseGeocode.php
  • RoutingV8.php
  • Weather.php

There is a duplicate code

        $cred = $this->c->getCredentials();
        if (! $cred->isBearer()) {
            if ($cred->getApiKey() !== "") {
                $retString = $this->addQueryParam($retString, "apiKey", $cred->getApiKey());
            }
            if ($cred->getAppId() !== "" && $cred->getAppCode() !== "") {
                $retString = $this->addQueryParam($retString, "app_id", $cred->getAppId());
                $retString = $this->addQueryParam($retString, "app_code", $cred->getAppCode());
            }
        }

Create a method in the parent class (RestClient) to return the $retString with the right query params (for the method implementation, reuse the duplicate piece of code and then in the "caller", call the method instead of that piece of code)
The method name : makeCredentialQueryParams($retString,): returns $retString with appended credentials

Add Map Image API usage documentation in Readme.md

In readme file, after "Isoline API" section and before "Useful reference" section add "Map Image API" to show some usage of MapImage class.
Use examples/20_map_image.php file to see some example of MapImage usage.

Add phpcs to composer.json

Add the codesniffer package in dev section.
In composer.json , in require-dev section, add squizlabs/php_codesniffer package:

{
    "require-dev": {
        "squizlabs/php_codesniffer": "3.*"
    }
}

So after that you can execute vendor/bin/phpcs.

Implement Endpoint HERE Map Image API

Implement Endpoint integration for HERE Map Image API
API Documentation URL: https://developer.here.com/documentation/map-image/dev_guide/topics/what-is.html

Example:
https://image.maps.ls.hereapi.com/mia/1.6/mapview
?apiKey={YOUR_API_KEY}
&c=47.8,13.033

Method: GET

Parameters to implement:

  • c center in format lat,lng
  • h hight if image
  • w width
  • u (10k) zoom in terms of km

For base url, path etc:
https://developer.here.com/documentation/map-image/dev_guide/topics/request-constructing.html

Update contributing.md for hacktoberfest

Replace Requirements section in CONTRIBUTING.md file with:

## Open a Pull Request

In order to maintain consistency in the source code we are following PSR12 coding standard, and using PHP stan for static code analysis.
You can use the command:

make allcheck

to launch
- **[PSR-12 Coding Standard](https://www.php-fig.org/psr/psr-12/)**, under the hood is used [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer);
- **PHPstan** with [level 7](https://phpstan.org/user-guide/rule-levels)
- **Phpunit** to execute all tests from ./tests/*

I suggest to launch *make allcheck* before to commit or before to create PR.

If you want to work on a PR, I suggest you to creating a new branch starting from **master branch**, and use it also when you will submit your new **P**ull **R**equest on the original repository.

If you want to contribute with an high quality PR, I suggest you to focus not just on the source code but also:

- **Add tests!** - Your patch won't be accepted if it doesn't have tests.

- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.

- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.

- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.

- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.

fix phpunit.xml.dist file

Running tests (PHPUnit 8) we have:

  Warning - The configuration file did not pass validation!
  The following problems have been detected:

  Line 25:
  - Element 'log', attribute 'charset': The attribute 'charset' is not allowed.
  - Element 'log', attribute 'yui': The attribute 'yui' is not allowed.
  - Element 'log', attribute 'highlight': The attribute 'highlight' is not allowed.

  Test results may not be as expected.

For now is it enough to replace this line:

<log type="coverage-html" target="build/coverage" charset="UTF-8" yui="true" highlight="true"/>

with this one:

<log type="coverage-html" target="build/coverage"/>

XyzConfig.php use Environment::getEnv() instead of getenv()

In XyzConfig we are still using getenv().
Replace getenv function:

$this->hostname = getenv("XYZ_API_HOSTNAME") ?: self::HOST_PROD;

with the new method:

$this->hostname = Environment::getEnv("XYZ_API_HOSTNAME", self::HOST_PROD);

In order to use Environment class you need to import the right class:

use HiFolks\Milk\Utils\Environment;

Php 7.2 compatibility XyzSpaceFeatureEditor.php

Php 7.2 compatibility

Parse error: syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST) in ./src/Here/Xyz/Space/XyzSpaceFeatureEditor.php on line 17
Errors parsing ./src/Here/Xyz/Space/XyzSpaceFeatureEditor.php

Php 7.2 compatibility XyzCredentials.php

Php 7.2 compatibility:

Parse error: syntax error, unexpected 'string' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in ./src/Here/Xyz/Common/XyzCredentials.php on line 7
Errors parsing ./src/Here/Xyz/Common/XyzCredentials.php

Fix standard=PSR12

Fix waring / error following indications provided by:

phpcs --standard=PSR12 src

phpstan level 6

Update code in order to resolve all warnings provided by phpstan with level=6

Fix for php 7.2 compatibility XyzSpaceStatistics.php

Fix for php 7.2 compatibility:

Parse error: syntax error, unexpected 'bool' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in ./src/Here/Xyz/Space/XyzSpaceStatistics.php on line 16
Errors parsing ./src/Here/Xyz/Space/XyzSpaceStatistics.php

Add the missing parameter avoid to Routing API V8

Add the missing parameter avoid to Routing API V8
API Documentation URL: https://developer.here.com/documentation/routing-api/8.9.1/api-reference-swagger.html

Method: GET

Parameters to implement:

  • avoid

Value for the parameter:

  • Avoid routes that violate certain features of road network or that go through user-specified geographical bounding box.

Specify properties using array notation like avoid[features]=controlledAccessHighway,tunnel

avoid[features]

A comma separated list of features that routes will avoid.

  • seasonalClosure
  • tollRoad
  • controlledAccessHighway
  • ferry
  • carShuttleTrain
  • tunnel
  • dirtRoad
  • difficultTurns

avoid[areas]

A pipe separated list of user defined areas that routes will avoid to go through.

Format: {shape1}|{shape2}|{shape3}...

Supported shape format:

Bounding box - A rectangular area on earth defined by a comma separated list of two latitude and two longitude values.
Format: bbox:{west},{south},{east},{north}
{west} - Longitude value of the westernmost point of the area.
{south} - Latitude value of the southernmost point of the area.
{east} - Longitude value of the easternmost point of the area.
{north} - Latitude value of the northernmost point of the area.
Example: bbox:13.082,52.416,13.628,52.626 - Bounding box of Berlin

Implement Endpoint Reverse Geocode

Implement Endpoint integration for Reverse Geocode.
Reverse Geocode endpoint documentation: https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-reverse-geocode-brief.html
API Documentation URL: https://developer.here.com/documentation/geocoding-search-api/api-reference-swagger.html

Method: GET
BASE URL: https://revgeocode.search.hereapi.com/v1/revgeocode

Parameters to implement:

  • at (required) "float,float" (url encode for comma) example: 48.2181679%2C16.3899064
  • limit "int": default is 1
  • lang "string" BCP47 compliant Language Codes

Start creating src/Here/RestApi/ReverseGeocode.php from src/Here/RestApi/Geocode.php

Improve documentation for Weather API in readme.md

In readme.md file, in Weather API section, add some information about Weather class methods like:

  • productObservation()
  • productAlerts()
  • productForecast7days()
  • productForecast7daysSimple()
  • productForecastAstronomy()
  • productForecastHourly()
  • productNwsAlerts()

Considering these notes:

     * Set the product for the Weather API
     * A parameter identifying the type of report to obtain.
     * The possible values are as follows:
     * - observation – current weather conditions from the eight closest locations to the specified location
     * - forecast_7days – morning, afternoon, evening and night weather forecasts for the next seven days.
     * - forecast_7days_simple – daily weather forecasts for the next seven days
     * - forecast_hourly – hourly weather forecasts for the next seven days
     * - forecast_astronomy – information on when the sun and moon rise and set,
     * and on the phase of the moon for the next seven days
     * - alerts – forecasted weather alerts for the next 24 hours
     * - nws_alerts – all active watches and warnings for the US and Canada

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.