Challenges in Defining Variables in Javascript and Actioscript 3

Currently, I am facing an issue while setting a variable through a javascript method call. Despite my attempts, it seems like the traditional approach using swLiveConnect is no longer effective and now my way is considered the correct way. Below are snippets of my javascript function and actionscript code. As someone new to actionscript, I find myself confused by this situation and seek guidance from more experienced individuals in the field.

Actionscript

//==========================================================
function decide_proposal(e:Event):void {
//==========================================================
    var address1:String = form1.project_address.text + ", " + form1.project_city.text + ", " + form1.project_state.text + ", " + form1.project_zip.text;
    var distance:Number = ExternalInterface.call("showLocation(" + address1 + ")");

    var commit:String = e.currentTarget.name;
    if (form1.stories.value >= 2.5 || form1.wood_no.selected || form1.framed_sqft.value >= 5000 || form1.roof_slope.value < 3 || form1.civil.selected || form1.cmt.selected || form1.commercial.selected || form1.c.selected || distance >= 180 || form1.bore_holes1.value >= 4) {
      send_proposal(e);
    } else if (commit == "quote") {
      perform_calculations(distance);
    } else {
      send_proposal(e);
    }
}

Javascript

var geocoder;
var location1;


function initialize() {
    geocoder = new GClientGeocoder();
}
function showLocation(address) {
    var locations = 0;
    geocoder.getLocations(address, function (response) {
        if (!response || response.Status.code != 200)
        {
            alert("There was an error");
        }
        else
        {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0]};
        }
    });
    var glatlng1 = new GLatLng(location1.lat, location1.lon);
    var brenham = new GLatLng(30.152289,-96.384881);
    var college_station = new GLatLng(30.610584,-96.306002);
    var miledistance1 = glatlng1.distanceFrom(brenham);
    var miledistance2 = glatlng1.distanceFrom(college_station);

    if (miledistance1 <= miledistance2) {
        locations = (miledistance1 * .000621371192);
    } else {
        locations = (miledistance2 * .000621371192);
    }
    return locations;
}
window.onload=function() {initialize();}

I have a strong feeling that the issue lies with the 'return' statement, however, I am unsure. I have double-checked the address being passed to the function and it appears to be correct. Upon tracing the value of distance before and after the call, I noticed it changes from NaN to 0. Despite Firebug showing the correct number, I remain puzzled.

Answer №1

It is crucial to include allowScriptAccess="always" in the HTML object/embed code for seamless functionality.

Answer №2

Perhaps you could attempt the following approach:

function displayLocation(address) {
    var locations = geocoder.getLocations(address, function (response) {
        if (!response || response.Status.code != 200)
        {
            alert("An error occurred");
        }
        else
        {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0]};
            var glatlng1 = new GLatLng(location1.lat, location1.lon);
            var cityA = new GLatLng(30.152289,-96.384881);
            var cityB = new GLatLng(30.610584,-96.306002);
            var distance1 = glatlng1.distanceFrom(cityA);
            var distance2 = glatlng1.distanceFrom(cityB);

            if (distance1 <= distance2) {
                return (distance1 * .000621371192);
            } else {
                return (distance2 * .000621371192);
            }
        }
    });
    return locations;
}

Answer №3

The problem seems to be stemming from the fact that geocoder.getLocations is failing to return the value of the function you provided to it. One potential solution would be to implement a closure:

function locateAddress(address) {
    var result;
    geocoder.getLocations(address, function (response) {
                                       ... // avoid re-declaring 'var result' here
                                       result = ...
                                   });
    return result;
}

Answer №4

It turned out the solution was quite straightforward. The issue stemmed from incorrectly passing the parameters to the function. Here's the correct way to do it:

    let result = ExternalInterface.call("displayMap", location);

And just like that, problem solved!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issu ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

Steps for Including Headers or Categories When Choosing Specific Ranges in Outcome

Is there a way to include headers like DATE, TOTAL, NAME, etc. when displaying categories? Currently, only the results are visible. function showInputBox(){ var ui = SpreadsheetApp.getUi(); var input = ui.prompt("Please enter your rep name.",u ...

Tips for preventing the [Vue warn] message in custom directive implementation

I've encountered an issue with a custom directive that I created. Despite it functioning properly, when running the mocha test for the component utilizing this directive, I received a warning message stating [Vue warn]: Failed to resolve directive: sc ...

The necessity of enclosing const names in curly braces in ReactJS

display () { const { parameters } = this.props.parameters return ( <div>{ parameters.post }</div> ) } Is there a specific reason why the parameters must be enclosed in curly brackets? Couldn't it simply be 'const params = th ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

What is the best way to prompt a jQuery plugin to update the information it has retrieved?

I'm currently working on implementing jQuery Pagination along with a popup form. My question is, after saving data in the form, how can I refresh the Pagination plugin to only load the data for the current page without having to refresh the entire web ...

Dealing with multiple v-on:click events in Vue.js

Can I add multiple v-on:click events to the same element? I want to toggle a navigation menu and trigger a CSS animation on the element that toggles the navigation. <template> <div> <nav v-if="visible"> <ul&g ...

What are some ways I can incorporate image sprites into my code?

I need assistance integrating image sprites into my code. How can I implement them and set everything up properly? I recently learned about using image sprites to resolve a specific issue, but I am unsure of the steps needed to configure them correctly. ...

Tips for seamlessly playing flowplayer while an mp4 file is loading?

Is there a way for the video to play while it is buffering, rather than waiting for the mp4 to be fully loaded? Thank you. ...

Tips for replicating the functionality of the F5 key when refreshing in AngularJs

Is there a way to achieve the same effect as using ui-sref-opts="{reload: true}" or pressing F5, but from within my controller? I attempted the following code: $state.transitionTo(myStateIWhantToReload, $stateParams, {reload:true, inherit:false}) Ho ...

Pattern matching tool for identifying React components with an unlimited number of properties

Currently diving into MDX and experimenting with Regex to extract details on React components from Markdown files. The regex pattern I'm aiming for should: Detect all types of React components This includes identifying the opening tag <Component ...

(React Native Gesture Handler) Attempted to directly invoke a function from a separate thread

I am attempting to modify the state based on a pan gesture in React Native Gesture Handler. const [localShowRecents, setLocalShowRecents] = useState(false) const translateY = useSharedValue(0); const gesture = Gesture.Pan() .onStart(() => { ...

Make sure that only one viewmodel property has insertMessages set to false in Knockout.js

Is it achievable to customize the insertMessages property to false for a specific view model property using Knockout.js instead of setting it globally using ko.validation.init({ insertMessages: false });? I am attempting to set insertMessages to false only ...

Having trouble making event listeners work with React useState in Next.js?

I'm currently working on a webpage where I want to have a fixed hamburger icon in the top-right corner that, when clicked, opens a navbar. The navbar should close if the user clicks outside of it, and the hamburger icon should reappear. Since Next.js ...

Show the initial three divs first before implementing a toggle for the rest

My dashboard consists of multiple panels, each containing various items. Some panels have a large number of items. I am looking to display only the first three items in each panel and provide a toggle option to show/hide the rest. <div class="dashboa ...

Issue encountered in AngularJS while configuring resources for the action `query`: Anticipated response was an object, but received an array instead

I've been attempting to utilize Angular 1.3 to access a REST service, but I keep encountering an error stating "Error: error:badcfg Response does not match configured parameter". My suspicion lies in the controller where I invoke $scope.data. Even th ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

Error: The object being referenced (scope.awesomeThings) is undefined and unable to be evaluated

Each time I run the grunt test command, I encounter this error. I set up a project using yo angular and attempted to execute the example code provided in Yeoman's scaffold. Something seems to have gone awry here - below is the code snippet that I trie ...

Tips for creating a floating navbar with separated lists using Bootstrap 4

Struggling to position my navbar to the right and separate the list within the navbar. Despite multiple attempts, I can't seem to get it right. Here is a snippet of the code I've been working on: here is what I'm trying to achieve $def with ...