<script>

    let map;
    let marker;


    function initMap() {
        var opt = {
            center: new google.maps.LatLng($("#latitude").val(), $("#longitude").val()),
            zoom: 15,
            streetViewControl: true,
            mapTypeControl: false
        };

        map = new google.maps.Map(document.getElementById("map"), opt);
        var markerOpts = {
            title: $(document.getElementById("title")).val(),
            position: opt.center,
            draggable: true,
            map: map
        };

        displayPlace();
        addListener();

        const geocoder = new google.maps.Geocoder();
        document.getElementById("submit-geoloc").addEventListener("click", () => {
            geocodeAddress(geocoder, map);
        });
    }

    function displayPlace() {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng($("#latitude").val(), $("#longitude").val()),
            map: map,
            draggable: true,
            title: $(document.getElementById("title")).val()
        });
    }

    function clearMarkers(map) {
        marker.setMap(map);
        marker = "";
    }

    function geocodeAddress(geocoder, resultsMap) {
        const address = document.getElementById("address1").value + ', ' + document.getElementById("zipcode").value + ' ' + document.getElementById("city").value;
        geocoder.geocode({ address: address }, (results, status) => {
            if (status === "OK") {

                clearMarkers(null);

                resultsMap.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                    map: resultsMap,
                    position: results[0].geometry.location,
                    draggable: true
                });
                $("#latitude").val(results[0].geometry.location.lat);
                $("#longitude").val(results[0].geometry.location.lng);
                addListener();
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }

    function addListener() {
        google.maps.event.addListener(marker, 'dragend', function(evt) {
            $("#latitude").val(evt.latLng.lat());
            $("#longitude").val(evt.latLng.lng());
        });
    }

</script>