/** * {@inheritdoc} */ public function locate($query) { $request = $this->client->get($this->baseUrl, [], ['query' => ['q' => $query, 'format' => 'json', 'addressdetails' => 1]]); $this->client->send($request); $response = $request->getResponse(); if ($response->getStatusCode() != 200) { throw new HttpException($response->getStatusCode(), sprintf('Server at "%s" returned HTTP "%s". Body: ', $client->getUrl(), $response->getStatusCode())); } $results = $request->getResponse()->json(); $response = new GeolocatorResponse(); foreach ($results as $result) { $location = new GeolocatorLocation(); foreach (['setStreet' => 'road', 'setNumber' => 'house_number', 'setCode' => 'postcode', 'setTown' => 'city', 'setCountry' => 'country_code'] as $method => $key) { if (isset($result['address'][$key])) { $location->{$method}($result['address'][$key]); } } $location->setId($result['place_id']); $location->setLongitude($result['lon']); $location->setLatitude($result['lat']); $location->setDisplayTitle($result['display_name']); $response->addLocation($location); } return $response; }
/** * {@inheritDoc} */ public function locate($query) { $endpoint = self::ENDPOINT; if ($this->apiKey) { $endpoint .= '?key=' . $this->apiKey; } $request = $this->client->get($endpoint, [], ['query' => ['address' => $query]]); $this->client->send($request); $response = $request->getResponse(); if ($response->getStatusCode() != 200) { throw new GeolocatorHttpException($response->getStatusCode(), sprintf('Server at "%s" returned HTTP "%s". Body: ', $client->getUrl(), $response->getStatusCode())); } $googleResponse = $request->getResponse()->json(); $response = new GeolocatorResponse(); if ($googleResponse['status'] != 'OK') { return $response; } $results = $googleResponse['results']; foreach ($results as $result) { $location = new GeolocatorLocation(); $map = []; foreach ($result['address_components'] as $component) { foreach ($component['types'] as $type) { if (isset($map[$type])) { $map[$type][] = $component; } else { $map[$type] = [$component]; } } } // google provides no ID - so we just make one up ... $location->setId(md5(serialize($result))); $location->setDisplayTitle($result['formatted_address']); foreach (['route' => 'setStreet', 'street_number' => 'setNumber', 'postal_code' => 'setCode', 'locality' => 'setTown', 'country' => 'setCountry'] as $field => $method) { if (isset($map[$field])) { $parts = []; foreach ($map[$field] as $fieldValue) { $parts[] = $fieldValue['long_name']; } $location->{$method}(implode(', ', $parts)); } } $geometry = $result['geometry']; $location->setLongitude($geometry['location']['lng']); $location->setLatitude($geometry['location']['lat']); $response->addLocation($location); } return $response; }