使用按钮onclick调用javascript函数

时间:2015-08-12 00:27:52

标签: javascript

geocoder = new google.maps.Geocoder();


if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction() {
    y.innerHTML = ("Geocoder failed");
}


var city = document.getElementById("location_city");
var latitude = document.getElementById("location_lat");
var longitude = document.getElementById("location_lng");


function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({
        'latLng': latlng
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results)
            if (results[1]) {
                //formatted address
                city.innerHTML = '<input type="text" name="city" value="' + (results[1].address_components[1].long_name) + ', ' + (results[1].address_components[2].short_name) + ', ' + (results[1].address_components[4].long_name) + '">'
                latitude.innerHTML = '<input type="text" name="city" value="' + lat + '">'
                longitude.innerHTML = '<input type="text" name="city" value="' + lng + '">'




            } else {
                y.innerHTML = ("No results found");
            }
        } else {
            y.innerHTML = ("Geocoder failed due to: " + status);
        }
    });
}

我尝试了一切,但我做不到。如何使用<button onclick = "try ( ) " value = "try ( ) " >

调用此函数

1 个答案:

答案 0 :(得分:1)

假设您的按钮具有ID(<button id=theId>Press here</button>),您可以使用.js文件或html中的javascript进行连接:

<script>
window.addEventListener('load',function(){ // when all is ready:
  var myButton = document.getElementById('theId');
  myButton.addEventListener('click',function(){
    // put here your code:

    var geocoder = new google.maps.Geocoder();

    if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
    }

    // etc!
  });
});
</script>