'How to limit the number of characters in laravel to convert to URL

I am using the google geocoding API to get latitude and longitude of addresses, the problem is that it is for Japanese users, which have "special" characters and when I use the service, the URL is too long

that results in a ZERO_RESULTS response

{
   "results" : [],
   "status" : "ZERO_RESULTS"
}

instead, if I delete some characters, I do get the results I want, what I'm looking for is to achieve that, for example

$customerAddress = "日本 〒462-0825 愛知県 名古屋市北区 大曽根3丁目 13-2V-Handsビル 1F"

do not exceed the number of characters allowed by the URL, which in the end I end up putting together like this

$geocodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=$customerAddress&key=$apiKey";

it doesn't matter if i remove characters from the end, but I need the address to not be SO specific so it can fit in the url

with this tool, we can verify what I say when placing the example address, we receive ZERO_RESULTS until we delete part of the text

how could I do it?

here is more documentation of the construction of the URL

URL encode to verify that it is too long by placing Japanese characters



Solution 1:[1]

You can use the Laravel Str helper to limit your string like this:

use Illuminate\Support\Str;

$rawCustomerAddress = "a very long address";
$maxAddressLength = 200;

$customerAddress = Str::limit($rawCustomerAddress, $maxAddressLength);

$geocodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=$customerAddress&key=$apiKey";

More details in the documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1