Google Maps API's fitBounds function is returning a location of 0,0 as a result

I have been experimenting with the code provided below in an attempt to adjust the map bounds to fit the markers:

var latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend(latlng);    
map.fitBounds(latlngbounds);    

However, I am encountering an issue where the map consistently zooms to location 0,0.

Update 1: Interestingly, this seems to be functioning properly in IE9 but not in Chrome. Upon inspecting Chrome Developer mode, I received the following error message:

Port error: Could not establish connection. Receiving end does not exist.

Update 2: After refreshing the page in IE9, the functionality also ceased to work.

Here is the code I am utilizing. I suspect there may be a fundamental mistake I am making?

//variables
var map;
var markers = [];
var latlngbounds;
//initialize google map
function initialize()
{
    var myOptions = {
        center: new google.maps.LatLng(-26.17706, 28.34613),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP};

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    latlngbounds = new google.maps.LatLngBounds();

    //display markers
    updateMarkersDisplayed(); 
}

//displays google map after site load complete
google.maps.event.addDomListener(window, 'load', initialize);

//retrieves markers for map
function updateMarkersDisplayed()
{
    //php get url
    var searchUrl = 'getCoords.php';

    downloadUrl(searchUrl, function(data) {
        var xml = parseXml(data);   
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markerNodes.length; i++) {
            var id = markerNodes[i].getAttribute("device_id");
            var latlng = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")),
                parseFloat(markerNodes[i].getAttribute("lng")));

            createMarker(latlng, id);      
            latlngbounds.extend(latlng);    
        }
    }); 
    //zoom map to display all markers
    map.fitBounds(latlngbounds);    
}

//create marker and display on map if not already visible
function createMarker(latlng, id) {      

    var iconUrl = 'images/phones.png';              
    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        title: id,
        icon: iconUrl
    });     

    markers.push(marker);   
    markers[markers.length-1].setMap[map];

}

//download xml file containing markers specified by the GET parameters contained in the url passed
function downloadUrl(url,callback)
{
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (request.readyState == 4) 
        {
            request.onreadystatechange = doNothing;
            callback(request.responseText, request.status);
        }
    };

    request.open('GET', url, true);
    request.send(null);
}

//parse text returned by php script
function parseXml(str) {
    if (window.ActiveXObject) 
    {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    } 
    else if (window.DOMParser) 
    {
        return (new DOMParser).parseFromString(str, 'text/xml');
    }
}

//capture extra XMLHttpRequest responses
function doNothing() {}

Answer №1

An empty google.maps.LatLngBounds at coordinates 0,0 indicates a lack of defined boundaries on the map.

If certain browsers are not functioning properly with your marker data in XML format, try directing those browsers to the XML feed and resolving any issues identified.

Answer №2

After encountering issues with the fitBounds function being called before the XML download was completed, I made a quick adjustment by moving the map.fitBounds(latlngbounds); inside the

downloadUrl(searchUrl, function(data) {
function.

    downloadUrl(searchUrl, function(data) {
        var xml = parseXml(data);   
        var markerNodes = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markerNodes.length; i++) {
            var id = markerNodes[i].getAttribute("device_id");
            var latlng = new google.maps.LatLng(
                parseFloat(markerNodes[i].getAttribute("lat")),
                parseFloat(markerNodes[i].getAttribute("lng")));

            bounds.extend(latlng);      
            createMarker(latlng, id);           
        }
        //zoom map to display all markers
        map.fitBounds(bounds);
    });     

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

Guide to automatically fill in a datetime-local field in an EJS form

Currently, I am working on a form that needs to be pre-populated with information from the database for users to view and edit. Everything is populating correctly except for a datetime-local variable. It's causing me some confusion. Here is the EJS fo ...

Having trouble populating data using JSON, the process is not functioning as expected

I need to dynamically populate a ul element with a list of options retrieved from JSON data. JSON Data: { "product": { "options":{ "42432":{ "id":42432, "title":"Choose your date", ...

A guide on efficiently storing and retrieving a webpage containing two angular2 components using local storage

I've been attempting to store and retrieve a page containing two angular2 components from local storage using the following code, but the component CSS is not being applied. Here is the code I'm using to save: localStorage.setItem('pageCon ...

Adding numerical values to circles can be achieved by implementing various methods,

I've been utilizing jsFiddle to generate multiple circles at specific locations. How can I include numbers within these circles so that each one is labeled with a number? Check out the jsfiddle code here function draw_circle(center_x, center_y){ ...

Understanding the usage of the "scripts" key in the package.json file

I'm curious about the purpose of the "scripts" key in the package.json file. While I was studying Angular 2, I encountered the following script in the package.json file and I wasn't sure what its function was. "scripts": { "postinstall": "npm ru ...

What is the best way to choose an Animatedmodal that can showcase various demos while using just one ID?

I am currently customizing my website and utilizing the AnimatedModal.js framework. I have successfully displayed content in one modal, but encountered difficulty when attempting to create multiple modals as they all share the same ID. My question is, how ...

Implement Material UI Card Component in your React Project

I'm currently working on a project that includes a page with expandable cards arranged in a list format. The code I have right now is not very scalable, as I keep adding individual card tags for each item. What I would like to achieve is to load data ...

Check to see if a value is present in JavaScript and proceed with submitting the form

I have a situation where I am trying to capture the browser location and post it to another page. The problem I'm facing is that JavaScript takes some time to retrieve the browser location, causing the form to be submitted before the location is obtai ...

Mastering the Art of Trimming with Jquery

function DisplayDataForEdit(id) { $("#editContainer").slideDown("medium"); var parentId ='item'+ id; var colIndex = 0; var $row = $("#" + parentId).parent().parent(); $row.find('td').each(f ...

Is the integration of async prior to the created method in Vue disrupting the lifecycle?

Is it advisable to include async before the created method in Vue.js? Won't this disrupt the Vue life cycle since using async makes it an asynchronous action that gets sent to the background queue, potentially allowing methods like mounted to execute ...

What is the best way to sort through an array using JavaScript?

Here's an array for you: values = ["10%", 1000, "5%", 2000] I'm looking to split this into two separate arrays like so: percentages = ["10%","5%"] numbers = [1000,2000] How can I achieve this using JavaSc ...

Is it possible to pass a PHP variable to JavaScript and then back to PHP?

I have a PHP variable named $author_email that I need to pass to a Javascript function when a button is clicked using HTML with the onclick event like this: onclick="searchEmail();". Is it possible to pass the variable like this instead? onclick="searchEma ...

JavaScript function that hides buttons when certain text appears

I created a function called hideButtons that hides buttons when certain text is found in the paragraph. The paragraph contains a list of names that the user either likes or dislikes, and once all names have been displayed, the buttons disappear. Currently ...

Adding multiple instances of a JPanel class without replacing them

Currently, I am facing an issue where I have created a class that extends JPanel (shown below) and I am attempting to add multiple instances of this class to another JPanel. public class DOBGui extends JPanel { private static String dayList[] = {bunch o ...

Creating a URL by formatting a JSON response

I am currently facing a major roadblock with formatting and processing a JSON response. Here is the sequence of steps I am following: Request data from a REST API endpoint (https://endpoint.com/api/v1/employee?id={username}) Receive the JSON response: {&q ...

Instead of pressing "w" to walk, simply click on the A-frame screen

I am diving into the amazing possibilities of A-frame. I've successfully implemented the WASD controls, which are working great. However, I am looking to enhance the experience by replicating the function of the W button when clicking on the screen, s ...

What is the reason for the request body being undefined?

I have a JavaScript file named index.js that contains: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./db'); const movieRouter = re ...

"Exploring One Direction: A bright spotlight on navigating with PointerLockControls in Threejs

My goal is to attach a directional flashlight to the camera (controls object) so that the beam always points towards the center of the screen. Here's the code I'm currently using: controls = new PointerLockControls( camera, document.body ); var f ...

Avoid data duplication or triplication by implementing a pop-up loop when adding new information

Seeking assistance in identifying the line of code that is causing data duplication or triplication when adding information in a pop-up form. The New/Update/Delete functions are functioning correctly, except for the Add function. The problem arises when i ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...