简体   繁体   中英

Is it possible to store the results from a class to a variable in Javascript

I'm trying to store the latitude and longitude values from the textboxes below locally so I can implement them into an ajax function but for some reason, they will not store into local variables.

屏幕截图

For example, in order to display these two values (calculated by converting the address from the search bar) in text boxes I've used the following code:

<p>Address: <input type="text" class="search_addr" size="45"/></p>
<p>Latitude: <input type="text" class="search_latitude" size="30"/></p>
<p>Longitude: <input type="text" class="search_longitude" size="30"/></p>

I'm finding it impossible to store the values represented by "search_latitude" and "search_longitude" into local variables. I've included a snippet of the javascript code below, but attempts I've made are as follows:

// This attempt returns the values as "[Object object]"
var Lat =  $('.search_latitude').val(marker.getPosition().lat());
var Long = $('.search_longitude').val(marker.getPosition().lng());

// And this attempt stops the map from loading and stops all functionality
var Lat = $('.search_latitude').val();
var Long = $('.search_longitude').val(); 

Being a beginner with javascript I've run out of ideas to solve this problem. Any tips?

<script>
var geocoder;
var map;
var marker;

/*
 * Google Map with marker
 */
function initialize() {
    var initialLat = $('.search_latitude').val();
    var initialLong = $('.search_longitude').val();
    initialLat = initialLat?initialLat:53.350140;
    initialLong = initialLong?initialLong:-6.266155;

    var latlng = new google.maps.LatLng(initialLat, initialLong);
    var options = {
        zoom: 11,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("geomap"), options);

    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
        position: latlng
    });

    google.maps.event.addListener(marker, "dragend", function () {
        var point = marker.getPosition();
        map.panTo(point);
        geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $('.search_addr').val(results[0].formatted_address);
                $('.search_latitude').val(marker.getPosition().lat());
                $('.search_longitude').val(marker.getPosition().lng());
            }
        });
    });

}

$(document).ready(function () {
    //load google map
    initialize();

    /*
     * autocomplete location search
     */
    var PostCodeid = '#search_location';
    $(function () {
        $(PostCodeid).autocomplete({
            source: function (request, response) {
                geocoder.geocode({
                    'address': request.term
                }, function (results, status) {
                    response($.map(results, function (item) {
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            lat: item.geometry.location.lat(),
                            lon: item.geometry.location.lng()
                        };
                    }));
                });
            },
            select: function (event, ui) {
                $('.search_addr').val(ui.item.value);
                $('.search_latitude').val(ui.item.lat);
                $('.search_longitude').val(ui.item.lon);
                var latlng = new google.maps.LatLng(ui.item.lat, ui.item.lon);
                marker.setPosition(latlng);
                initialize();
            }

        });
    });

    /*
     * Point location on google map
     */
    $('.get_map').click(function (e) {
        var address = $(PostCodeid).val();
        geocoder.geocode({'address': address}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $('.search_addr').val(results[0].formatted_address);
                $('.search_latitude').val(marker.getPosition().lat());
                $('.search_longitude').val(marker.getPosition().lng());
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
        e.preventDefault();
    });

    //Add listener to marker for reverse geocoding
    google.maps.event.addListener(marker, 'drag', function () {
        geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    $('.search_addr').val(results[0].formatted_address);
                    $('.search_latitude').val(marker.getPosition().lat());
                    $('.search_longitude').val(marker.getPosition().lng());
                }
            }
        });
    });
});

geocoder.geocode({
    'address': request.term,
    componentRestrictions: {country: "ie"}
})

function loginAlert(){
    alert("User must be logged in to view reports");
}

</script>

The jQuery val() function returns a jQuery object, not a string. Casting an object without a toString method to a string will show up as [Object object] . It seems like you're trying to do two things with one statement: (1) Write the latitude/longitude into the HTML element. (2) Write the latitude/longitude into a variable. Try doing these separately:

// (1) Write the latitude into the HTML element.    
$('.search_latitude').val(marker.getPosition().lat());
// (2) Write the latitude into a variable.
var Lat = marker.getPosition().lat();

// then perhaps check if the output is what you expected by viewing the developer console
console.log(Lat);

and then similarly for longitude.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM