-1

So i have a spring boot application kind of taxi web system, user has to fill in 2 fields: 'from' and 'where to go', then i convert these addresses to latlng and find route between them. it was working ok before now, so what happened is when i type address, it autocompletes with additional information like city and country (before was the same, worked fine but now it is broken, it uses ukrainian language and converts ukrainian letters somehow), and this information is converted to some symbols like:

origin input: 'вулиця Миколи Оводова, Вінниця, Вінницька область, Україна', destination input: 'проспект Космонавтів, 53, Вінниця, Вінницька область, Україна'. it what input types, then in application i receive this:

вулиця Миколи Оводова, Вінниця, Вінницька область, Україна

What can i do about this? i need exactly the same input like this: 'проспект Космонавтів, 53, Вінниця, Вінницька область, Україна' not unicode charachters

Code i have:

 @PostMapping(value = "/processInput", produces = "text/html")
    public String getOriginAndDestFromUser(@RequestParam String origin, @RequestParam String destination, Model model) throws IOException, ApiException, InterruptedException {
        model.addAttribute("origin", origin);
        model.addAttribute("destination", destination);
        model.addAttribute("cars", carService.findAll());
        model.addAttribute("carLocations", CarCoordinatsUtils.getCoords());

        String originPlaceId = getGeocodeCoordinates(origin);
        String destPlaceId = getGeocodeCoordinates(destination);
        model.addAttribute("originPlaceId", originPlaceId);
        model.addAttribute("destPlaceId", destPlaceId);

        return PagesConstants.RESPONSE_PAGE;
 public static String getGeocodeCoordinates(String address) throws InterruptedException, ApiException, IOException {
        GeocodingApiRequest request = GeocodingApi.newRequest(getGeoContext()).address(address);
        GeocodingResult result = request.await()[0];
        return result.geometry.location.toString();

    }

javascript map.html:

<script>
    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 49.2331, lng: 28.4682},
            zoom: 13
        });
        var card = document.getElementById('pac-card');
        var input = document.getElementById('pac-input');
        var dest = document.getElementById('pac-dest');
        var types = document.getElementById('type-selector');
        var strictBounds = document.getElementById('strict-bounds-selector');

        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

        var autocomplete = new google.maps.places.Autocomplete(input);
        var autocomplete2 = new google.maps.places.Autocomplete(dest);

        // Bind the map's bounds (viewport) property to the autocomplete object,
        // so that the autocomplete requests use the current map bounds for the
        // bounds option in the request.
        autocomplete.bindTo('bounds', map);

        // Set the data fields to return when the user selects a place.
        autocomplete.setFields(
            ['address_components', 'geometry', 'icon', 'name']);

        var infowindow = new google.maps.InfoWindow();
        var infowindowContent = document.getElementById('infowindow-content');
        infowindow.setContent(infowindowContent);
        var marker = new google.maps.Marker({
            map: map,
            anchorPoint: new google.maps.Point(0, -29)
        });



        autocomplete.addListener('place_changed', function() {
            infowindow.close();
            marker.setVisible(false);
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                // User entered the name of a Place that was not suggested and
                // pressed the Enter key, or the Place Details request failed.
                window.alert("No details available for input: '" + place.name + "'");
                return;
            }

            // If the place has a geometry, then present it on a map.
            if (place.geometry.viewport) {
                map.fitBounds(place.geometry.viewport);
            } else {
                map.setCenter(place.geometry.location);
                map.setZoom(17);  // Why 17? Because it looks good.
            }
            marker.setPosition(place.geometry.location);
            marker.setVisible(true);

            var address = '';
            if (place.address_components) {
                address = [
                    (place.address_components[0] && place.address_components[0].short_name || ''),
                    (place.address_components[1] && place.address_components[1].short_name || ''),
                    (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
            }

            infowindowContent.children['place-icon'].src = place.icon;
            infowindowContent.children['place-name'].textContent = place.name;
            infowindowContent.children['place-address'].textContent = address;
            infowindow.open(map, marker);
        });

        // Sets a listener on a radio button to change the filter type on Places
        // Autocomplete.
        function setupClickListener(id, types) {
            var radioButton = document.getElementById(id);
            radioButton.addEventListener('click', function() {
                autocomplete.setTypes(types);
            });
        }

        setupClickListener('changetype-all', []);
        setupClickListener('changetype-address', ['address']);
        setupClickListener('changetype-establishment', ['establishment']);
        setupClickListener('changetype-geocode', ['geocode']);

        document.getElementById('use-strict-bounds')
            .addEventListener('click', function() {
                console.log('Checkbox clicked! New state=' + this.checked);
                autocomplete.setOptions({strictBounds: this.checked});
            });
    }
    var infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());

    }

    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
            'Error: The Geolocation service failed.' :
            'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
    }
</script>

Response.html

<script>
    var map;
    var start = document.getElementById("start");
    var end = document.getElementById("end");
    var origin = document.getElementById("origin").innerText;
    var destination = document.getElementById("destination").innerText;
    var originPlaceId = document.getElementById("originPlaceId").innerText;
    var destPlaceId = document.getElementById("destPlaceId").innerText;
    initMap();
    function initMap() {
        var directionsService = new google.maps.DirectionsService();
        var directionsRenderer = new google.maps.DirectionsRenderer();



        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: {lat: 49.2331, lng: 28.4682},
        });
        directionsRenderer.setMap(map);

        var onChangeHandler = function() {
            console.log('goes to here 1');
            calculateAndDisplayRoute(directionsService, directionsRenderer);
        };
        document.getElementById('showDirection').addEventListener('click', onChangeHandler);
    }

    function calculateAndDisplayRoute(directionsService, directionsRenderer) {
        console.log('goes to here 2');
        directionsService.route(
            {
                 origin: {query: document.getElementById("originPlaceId").innerText}, //45.65676020,-122.60382060
                 destination: {query: document.getElementById("destPlaceId").innerText}, //49.22513880,28.41919540//var end doesnt work here and request not found, should pass ltn and lng of start and dest and works fine
                //origin : {query: "49.2261393,28.4103459"},
                //destination : {query: "49.2250969,28.4187825"},
                travelMode: 'DRIVING'
            },
            function(response, status) {
                if (status === 'OK') {
                    console.log('goes to here 3');
                    directionsRenderer.setDirections(response);

                } else {
                    console.log('goes to here fail');
                    window.alert('Directions request failed due to ' + status);
                }
            });
    }
</script>

1 Answers1

0

What happens is that for some reason your parameter gets HTML-escaped. You can unescape it back by using class org.apache.commons.text.StringEscapeUtils from the library apache.commons/commons-text. Here is the code that does the trick:

private static void testUrlEncoding() {
    String actual = "Kosmonavtiv Avenue, 66, &#1042;&#1110;&#1085;&#1085;&#1080;&#1094;&#1103;, &#1042;&#1110;&#1085;&#1085;&#1080;&#1094;&#1100;&#1082;&#1072; &#1086;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;, &#1059;&#1082;&#1088;&#1072;&#1111;&#1085;&#1072;";
        String unescaped = StringEscapeUtils.unescapeHtml4(actual);
        System.out.println(unescaped);
}

And the output is:

Kosmonavtiv Avenue, 66, Вінниця, Вінницька область, Україна

The info found at: How to unescape HTML character entities in Java?

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36