adjustBounds and expand - appearing in an entirely new location

var classBounds = new google.maps.LatLngBounds();
var query = "";

query = "SELECT 'ROAD_NUMBER', 'geometry' FROM [TABLE_REFERENCE_ID] WHERE 'ROAD_NUMBER' CONTAINS IGNORING CASE '" + searchString + "' AND 'LINK_NUMBER' CONTAINS '" +searchStringLinkNo + "'";
var encodedQuery = encodeURIComponent(query);

// Create URL
var url = ['https://www.googleapis.com/fusiontables/v1/query'];
url.push('?sql=' + encodedQuery);
url.push('&key=[API_KEY]');
url.push('&callback=?');

// Perform JSONP request with jQuery
$.ajax({
    url: url.join(''),
    dataType: 'jsonp',
    success: function (data){

        var rows = data['rows'];

        if(rows){

            var classRoadGeo1       = rows[0][1].geometry.coordinates;
            var classRoadGeo2       = rows[rows.length - 1][1].geometry.coordinates;
            var classRoadGeoStart   = classRoadGeo1[0];
            var classRoadGeoEnd     = classRoadGeo2[classRoadGeo2.length - 1];

            var startHolder = classRoadGeoStart.toString();
            var endHolder = classRoadGeoEnd.toString();

            var bound1 = startHolder.split(",");
            var bound2 = endHolder.split(",");

            var coordinate1 = new google.maps.LatLng(bound1[1], bound1[0]);
            var coordinate2 = new google.maps.LatLng(bound2[1], bound2[0]);

            alert(bound1);
            alert(bound2);

            classBounds.extend(coordinate1);
            classBounds.extend(coordinate2);                

        }
        else{

            alert("Unable to find any stations for the selected criteria.");
        }
    }
}); 

map.fitBounds(classBounds);

}

The code above retrieves geometry information from a fusion table, converts it into string, and creates LatLng objects. However, when using fitBounds, it incorrectly centers on Papua New Guinea instead of Kiama in Sydney, Australia. No errors are displayed. Any suggestions on what may be causing this?

Answer №1

Due to the asynchronous nature of the ajax request, the bounds are not extended when map.fitBounds() is initially called. To ensure proper functionality, move the line "map.fitBounds(classBounds);" to the end of your if clause within the success function.

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

Enable automatic scrolling on a website using jQuery with the option to pause

I'm trying to implement a feature in jQuery where the web page auto-scrolls to a specific point, pauses for a moment, and then continues scrolling. It's like simulating a user scrolling down a page while reading an article - stopping and starting ...

Having trouble getting the auto complete feature to work in AngularJS with jQuery

I have been attempting for the last 5 hours without any success... Below is the code snippet: Within View: <input type="text" ng-model="foo" auto-complete/>Foo = {{foo}} Inside the controller: myapp.directive('autoComplete', functi ...

How to eliminate all <style> tags across the board using Regex in JavaScript

Is there a way to utilize regex in JavaScript for removing all instances of <style>, <style type="text/css">, </style>, and <style type="text/css"/>? I want the outcome to only present the CSS without any style tags. The code below ...

The ASP.NET webpage's AJAX call to a WebMethod was met with a timeout error

I have a web method on an ASP page that performs an operation taking around 200-300 seconds. [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string MyMethod(string requestObject) { // This is the ope ...

Exploring the combined application of the AND and OR operators in JavaScript programming

{Object.keys(groupByMonthApplicants).map((obj,i) => <div key={obj} style={(i > 0 && (this.state.selectedTabId !== 'rejected' || this.state.selectedTabId !== 'approved')) ? {paddingTop:'15px',background:&a ...

The TouchableOpacity function is triggered every time I press on the Textinput

Every time I press on a text input field, the login function is called This is the touchable statement: <TouchableOpacity style={InputFieldStyle.submitButton} onPress={this.login(this.state.email, this.state.password)}> <Text ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows use ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Preventing users from accessing the previous page via the browser back button after logging out in an AngularJS application

Currently, I have developed an angularjs web application and facing a challenge. After logout, I am looking to prevent users from navigating back to the previous page using the browser's back button. Ideally, I would like to display a customized messa ...

What are the reasons for avoiding placing CSS code directly within HTML?

Situation: My website is dynamically served, with all CSS and javascript directly embedded into the HTML document to optimize speed. Advantages: Reduces web requests Fewer files downloaded Speeds up webpage loading time Disadvantages: Potential cachin ...

What is the best way to incorporate the {id} property into my Next.js dynamic route using the Context API?

I am encountering an issue with passing the ${id} property to my dynamic route [id]>page.jsx, located within the CartItemPage.jsx file. The setup involves using the Context API, similar to React, where I maintain an array of CartItems to render the Cart ...

Using the JavaScript Reduce method to combine identical key values into an array

Hey there! Currently, I'm utilizing the reduce method to enhance the JSON structure of this specific dataset. info = [ { "0": "key1", "1": "value1" }, { "0": "key2", "1": "value2" }, { "0": "key3", "1": "value3" }, { "0": "key1", "1": "value ...

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...

Narrowing down types within an array of objects

I am encountering an issue with the following code snippet: const f = (x: unknown) => { if (!x || !Array.isArray(x)) { throw new Error("bad"); } for (const y of x) { if (!y || typeof y !== "object") { throw new E ...

Whenever I try to update my list of products, I encounter an error message stating that the property 'title' cannot be read because it is null

I am encountering an issue with editing data stored in the database. When attempting to edit the data, it is not displaying correctly and I am receiving a "cannot read property" error. HTML admin-products.component.html <p> <a routerLink="/ad ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

Even though I have properly set up the express.static() function and ensured that the path is correct, my initial app is still not serving the

Just like the title suggests, I am venturing into building my first node app and have come across an issue. Everything was working perfectly yesterday. However, when I booted up my PC today, I received the error message "Resource interpreted as Stylesheet ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

What is the best way to eliminate blank values ("") from an array?

I am working with a two-dimensional array that was generated from an HTML table using jQuery, but I have noticed that some values are empty and are displaying as "". How can I go about removing these empty values from the array? <table> ...