Converts the given address to lat/lng

@param string      $address The address to search
@param string|null $country The ISO 3166-1 alpha-2 country code to
restrict the search to

@return array|null
978569
public function getLatLngFromAddress ($address, $country = null)
	{
		try
		{
			return GeoService::latLngFromAddress($address, $country);
		}
		catch (Exception $e)
		{
			\Craft::error($e->getMessage(), 'simplemap');

			return [
				'lat' => '',
				'lng' => '',
			];
		}
	}
276666
public function format(Address $address)
    {
        $fields = [
            'p-street-address' => $address->getStreet(),
            'p-extended-address' => $address->getExtended(),
            'p-post-office-box' => $address->getPobox(),
            'p-locality' => $address->getLocality(),
            'p-region' => $address->getRegion(),
            'p-postal-code' => $address->getPostal(),
            'p-country' => $address->getCountry()
        ];
        $tags = [];
        foreach ($fields as $k => $v) {
            if (strlen($v) > 0) {
                $tags[] = '<span class="' . $k . '">' . htmlspecialchars($v) . '</span>';
            }
        }
        $geo = $address->getGeo();
        if ($geo !== null) {
            $tags[] = '<span class="p-geo">' . $this->geoFormatter->format($geo) . '</span>';
        }
        return '<span class="h-adr">' . implode(' ', $tags) . '</span>';
    }
549987
private function setAddress($address) {

        if(!$this->formatter) {
            $this->formatter = new StringFormatter();
        }

        $this->address = trim($this->formatter->format($address, '%S %n %z %L %C'));

        return $this;
    }
226018
public function retrieve($address) {
		/** @var \Geo\Model\Entity\GeocodedAddress $entity */
		$entity = $this->find()->where(['address' => $address])->first();
		if ($entity) {
			return $entity;
		}

		$result = $this->_execute($address);
		$address = $this->newEntity([
			'address' => $address
		]);
		if ($result) {
			$address->lat = $result->getLatitude();
			$address->lng = $result->getLongitude();
			$address->country = $result->getCountry()->getCode();

			$formatter = new StringFormatter();
			$address->formatted_address = $formatter->format($result, '%S %n, %z %L');
			$address->data = $result;
		}

		return $this->save($address);
	}
1312000
public function getPrivateKeyByAddress($address)
    {
        $args = [
            (string)$address
        ];

        $priv_key = null;
        try {
            $priv_key = $this->rpc->query("dumpPrivKey", $args);
        } catch (Exceptions\RPCException $e) {
            if ($e->getCode() != RPCErrorCodes::WALLET_ERROR) {
                throw $e;
            }
        }

        return $priv_key;
    }
1249274
protected function _execute($address) {
		/** @var \Geo\Model\Table\GeocodedAddressesTable|null $GeocodedAddresses */
		$GeocodedAddresses = null;
		if ($this->getConfig('cache')) {
			$GeocodedAddresses = TableRegistry::get('Geo.GeocodedAddresses');
			/** @var \Geo\Model\Entity\GeocodedAddress $result */
			$result = $GeocodedAddresses->find()->where(['address' => $address])->first();
			if ($result) {
				/** @var \Geocoder\Model\Address|null $data */
				$data = $result->data;
				return $data ?: null;
			}
		}

		try {
			$addresses = $this->_Geocoder->geocode($address);
		} catch (InconclusiveException $e) {
			$addresses = null;
		} catch (NotAccurateEnoughException $e) {
			$addresses = null;
		}
		$result = null;
		if ($addresses && $addresses->count() > 0) {
			$result = $addresses->first();
		}

		if ($this->getConfig('cache')) {
			/** @var \Geo\Model\Entity\GeocodedAddress $addressEntity */
			$addressEntity = $GeocodedAddresses->newEntity([
				'address' => $address
			]);
			if ($result) {
				$formatter = new StringFormatter();
				$addressEntity->formatted_address = $formatter->format($result, '%S %n, %z %L');
				$addressEntity->lat = $result->getLatitude();
				$addressEntity->lng = $result->getLongitude();
				$addressEntity->country = $result->getCountry()->getCode();
				$addressEntity->data = $result;
			}

			if (!$GeocodedAddresses->save($addressEntity, ['atomic' => false])) {
				throw new RuntimeException('Could not store geocoding cache data');
			}
		}

		return $result;
	}
1057087
public function getAddress($index)
    {
        if (!isset($this->addresses[$index])) {
            return null;
        }
        return $this->addresses[$index];
    }
1349408
protected function _geocode($entity, array $addressData) {
		$entityData = [
			'geocoder_result' => [],
		];

		$search = implode(' ', $addressData);
		if ($search === '') {
			if (!$this->_config['allowEmpty']) {
				return null;
			}

			return $entity;
		}

		$address = $this->_execute($search);
		if (!$address) {
			if ($this->_config['allowEmpty']) {
				return $entity;
			}
			if ($entity instanceof Entity) {
				$this->invalidate($entity);
			}
			return null;
		}

		if (!$this->_Geocoder->isExpectedType($address)) {
			if ($this->_config['allowEmpty']) {
				return $entity;
			}
			if ($entity instanceof Entity) {
				$this->invalidate($entity);
			}
			return null;
		}

		// Valid lat/lng found
		$entityData[$this->_config['lat']] = $address->getLatitude();
		$entityData[$this->_config['lng']] = $address->getLongitude();

		if (!empty($this->_config['formatted_address'])) {
			// Unfortunately, the formatted address of google is lost
			$formatter = new StringFormatter();
			$entityData[$this->_config['formatted_address']] = $formatter->format($address, '%S %n, %z %L');
		}

		$entityData['geocoder_result'] = $address->toArray();
		$entityData['geocoder_result']['address_data'] = implode(' ', $addressData);

		if (!empty($this->_config['update'])) {
			foreach ($this->_config['update'] as $key => $field) {
				//FIXME, not so easy with the new library
				if (!empty($geocode[$key])) {
					$entityData[$field] = $geocode[$key];
				}
			}
		}

		foreach ($entityData as $key => $value) {
			$entity[$key] = $value;
		}
		return $entity;
	}
733238
private function transformAddressesToArray($addresses): array
    {
        $transformed = [];
        foreach ($addresses as $address) {
            if (null === $address->getName()) {
                $transformed[] = $address->getEmail();

                continue;
            }

            $transformed[$address->getEmail()] = $address->getName();
        }

        return $transformed;
    }
1009861
protected function formatName(Location $address): string
    {
        $name = [];
        $array = $address->toArray();

        foreach (['streetNumber', 'streetName', 'postalCode', 'locality'] as $attr) {
            $name[] = $array[$attr];
        }

        if (isset($array['adminLevels'][2])) {
            $name[] = $array['adminLevels'][2]['name'];
        }

        if (isset($array['adminLevels'][1])) {
            $name[] = $array['adminLevels'][1]['name'];
        }

        $name[] = $array['country'];

        return implode(', ', array_filter($name));
    }
311554
public function getCodeFromCountry($country)
    {
        $output = 'OTH';
        if (array_key_exists($country, $this->countriesMapping)) {
            $output = $this->countriesMapping[$country];
        }

        return $output;
    }
970892
public function getMageRegionByAddress($address)
    {
        $map = $this->getIsoToMagentoMapping();

        $state = preg_replace("/{$address->getCountry()}\-/", "", $address->getState());

        /** @var \Magento\Directory\Model\ResourceModel\Region\Collection $set */
        /** @var \Magento\Directory\Model\Region $region */
        $set    = $this->regionFactory->create()->getCollection();
        $region = $set->addCountryFilter($address->getCountry())
                      ->addFieldToFilter('main_table.code', $state)
                      ->getFirstItem();

        // If no region was found
        if (!$region->getId() && !empty($state) && isset($map[$address->getCountry()][$state])) {
            $regionCode = $map[$address->getCountry()][$state];

            $set    = $this->regionFactory->create()->getCollection();
            $region = $set->addRegionCodeFilter($regionCode)->addCountryFilter($address->getCountry())->getFirstItem();
        }

        if (!$region->getId()) {
            $this->logger->error('Region not found, state provided: ' . $state . ' country: ' . $address->getCountry());
        }

        return $region;
    }
918461
public function country($country = null)
  {
    if (null === $country)
    {
      return $this->responseConfig['country'];
    }

    if (false === in_array(strtolower($country), $this->possibleLocations))
    {
      throw new InvalidArgumentException(sprintf(
        "Invalid Country-Code: %s! Possible Country-Codes: %s",
        $country,
        implode(', ', $this->possibleLocations)
      ));
    }

    $this->responseConfig['country'] = strtolower($country);

    return $this;
  }
24205
public static function toIso($country)
    {
        $table = array_flip(self::isoCodes());

        if (!array_key_exists($country, $table)) {
            return null;
        }

        return $table[$country];
    }
1135735
public function addressToPoint($address, $region = '')
    {
        // Get the URL for the Mapbox API
        $url = Config::inst()->get(__CLASS__, 'mapbox_api_url');
        $key = Config::inst()->get(__CLASS__, 'mapbox_api_key');

        if (!$url) {
            // If no URL configured. Stop.
            throw new Exception('No mapbox_api_url configured. This is not allowed.');
        }

        if (!$key) {
            // If no KEY configured. Stop.
            throw new Exception('No mapbox_api_key configured. This is not allowed.');
        }

        // Add params
        $queryVars = [
            'access_token' => $key,
            'type' => 'address',
        ];
        if ($region) {
            $queryVars['country'] = $region;
        }
        $url .= urlencode($address).'.json?'.http_build_query($queryVars);

        $client = new Client();
        $response = $client->get($url);
        if (!$response) {
            throw new GeocodeServiceException('No response.', 0, '');
        }
        $statusCode = $response->getStatusCode();
        if ($statusCode !== 200) {
            throw new GeocodeServiceException('Unexpected status code:'.$statusCode, $statusCode, '');
        }
        $responseBody = json_decode((string)$response->getBody());

        // Error handling
        if ($responseBody) {
            if (isset($responseBody->message)) {
                throw new GeocodeServiceException('Error message: '.$responseBody->message, $statusCode, $responseBody);
            }
            if (!isset($responseBody->features) || !count($responseBody->features) === 0) {
                throw new GeocodeServiceException('Zero results returned. Invalid status from response: '.$status, $statusCode, $responseBody);
            }
        } else {
            // Fallback to full string dump
            $text = trim($response->getBody());
            throw new GeocodeServiceException('Invalid response: '.$text, $statusCode, $responseBody);
        }

        // We take the first match, because that's most likely the best match
        $feature = reset($responseBody->features);
        list($lng, $lat) = $feature->geometry->coordinates;

        return [
            'lat' => (float)$lat,
            'lng' => (float)$lng
        ];
    }
565116
public function trimAddress($address)
    {
        $address = trim($address);

        return (($address[0] == '<') && (substr($address, -1) == '>'))
            ? substr($address, 1, -1)
            : $address;
    }
154079
public function convertAddressFromAmazonObjectToLocal(OffAmazonPaymentsService_Model_Address $address, $targetAddressType)
    {
        return $this->convertAddressFromAmazonToLocal(
            array(
                'Name' => $address->getName(),
                'AddressLine1' => $address->getAddressLine1(),
                'AddressLine2' => $address->getAddressLine2(),
                'AddressLine3' => $address->getAddressLine3(),
                'County' => $address->getCounty(),
                'District' => $address->getDistrict(),
                'StateOrRegion' => $address->getStateOrRegion(),
                'City' => $address->getCity(),
                'PostalCode' => $address->getPostalCode(),
                'Phone' => $address->getPhone(),
                'CountryCode' => $address->getCountryCode(),
            ),
            $targetAddressType
        );
    }