View the center of the map on Google Maps from a different VARIABLE

Here is the code I've been working on:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps AJAX + mySQL/PHP Example</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC-dbN2gdvXsx09jfJHmNc8"
            type="text/javascript"></script>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript">
    //<![CDATA[
$(document).ready(function() {


var customIcons = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';


var map = new google.maps.Map(document.getElementById("map"), {       
        center: new google.maps.LatLng(-6.289796, 106.822370),
        zoom: 11,
        mapTypeId: 'roadmap'
      });

      //^ HOW CAN THE CENTER VALUE IN VAR POINT BE USED IN FUNCTION LOAD()? ??? ^ //
var markarray=[]
    function load() {

           for (var i = 0; i < markarray.length; i++) {
             markarray[i].setMap(null);
             } 
            markarray = [];
      console.log("ok")
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("http://localhost/maps6/genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          //var name = markers[i].getAttribute("name");
          var date_taken = markers[i].getAttribute("date_taken");
          //var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
                  //^ HOW TO GET THE POINT VALUE TO CENTER IN VAR MAP ???? ^ //
          var html = "<b>" + name + "</b> <br/>" + date_taken;
          var icon = 'mark.png';
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: 'mark.png',
            animation: google.maps.Animation.BOUNCE,
            shadow: icon.shadow
          });
          markarray.push(marker);
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    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, request.status);
        }
      };

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

    function doNothing() {}

    $("#BtnClicked").live('click',function(){load();});


  setInterval(function() {load();},3000);

});

 //]]>
  </script>

  </head>

  <body>
    <div id="map" style="width: 1280px; height: 720px"></div>
    <a href="#" id="BtnClicked">test</a>
  </body>
</html>

Upon running the code, the result can be viewed here: https://i.sstatic.net/mLhOy.png

^ The green marker automatically updates its position based on MySQL Database without having to reload the entire Google Maps page.

Therefore, I am curious about how to retrieve the Google Maps CENTER (in var map) from VAR POINT within the function load()

Answer №1

Hats off to geocodezip for revealing the solution to this issue - simply include

map.setCenter(marker.getPosition());
after

markarray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);

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

Select values to Component from an array contained within an array of objects

Each user possesses a unique list of tags, and every item owned by the user can be associated with multiple tags from this list. In this scenario, I am attempting to display all the tags belonging to a user for a particular item. If the item has a tag tha ...

Getting the userID variable in a pop-up modal in PHP

On a page, employee information is displayed after retrieval from a database using a foreach() loop to show employees matching the search criteria. See image below for an example: https://i.sstatic.net/OPzVS.jpg Clicking a button triggers a simple Bootst ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

Step-by-step guide on retrieving the button text by utilizing a method call

Currently, I am troubleshooting a demo and I'm puzzled as to why the text of the #add-point button is not displaying. $("#add-point").on("click", function(){ activatePointTool(); }); function activatePointTool() { var tool = $(this).text().toU ...

Mastering the art of square bracket destructuring in React through deep comprehension of the concept

import React, { useEffect, useState } from 'react' import { Text } from 'react-native' export default function Counter() { const [count, setCount] = useState(0) useEffect(() => { const id = setInterval(() => setCount((co ...

Unusual behavior of the splice function when applied to child nodes

Inside the given ul element, there are four li child elements. If the code below is run in the console: var a = document.getElementsByTagName("ul")[0]; a.childNodes.splice(1, 2, "abc", "cde"); An error will appear with this message: TypeError: a.childNo ...

Tips for eliminating inline scripts or HTML injections from input text using JavaScript or jQuery

Although this type of question may have been asked multiple times before, I am confident that this one is unique. On the server side, I have an Input TextArea control and I am attempting to eliminate all inline scripts or HTML injections. I have successful ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

"Troubleshooting PhoneGap: The Mystery Behind Why Your AJAX Post Request Isn't

I have been experimenting with phonegap and jquery. One particular code snippet is functioning correctly: $.ajax({url: 'samplefile.html'}); However, this specific code snippet is not working as expected: $.ajax({url: 'samplefile.html&apo ...

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

Creating a Fresh Row with Form Inputs and a PHP Variable

I am working on a table where pressing a button adds a new row. Here is the code snippet: <table id='editTable' width='655' border='1'>"; <tr><th width='330' align='left'>Expense Descript ...

What are the benefits of incorporating function calls within {{}} (Curly Brackets)?

Is it considered best practice to use function calls within {{}} (Curly Brackets)? Is there a recommended way to achieve this within the component, possibly utilizing ngOnChanges or similar methods? Template <div class="container"> {{ processB ...

Unable to download and install jspdf version 1.5.3

Currently, I am facing an issue where I need to convert HTML to PDF using jspdf 1.5.2. However, I am encountering an error that says "Cannot read property 'charAt' of undefined" when trying to utilize html2canvas. When attempting to upgrade to j ...

Accelerating Ajax completion DOM modifications

I've implemented an AJAX call on my webpage that retrieves table rows and inserts them into a table upon successful completion. The current code snippet is provided below: function GetDPRecords(Perso) { //alert(Perso); $Records = $(&a ...

What is the syntax for invoking a javascript/typescript constructor while providing an object as an argument?

How should I structure my constructor if it will be invoked with the following code: const user = new User({ username, email }) Both `username` and `email` are of type string. Update: Here is how you can implement this in TypeScript: interface U ...

Which delivers better performance: HTTP request from server or client?

Considering the optimal performance, is there a difference in using Angular's HTTP request within a MEAN-stack environment compared to utilizing Request.js or similar for server requests? ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...

PHP MySQL table submission button

Here is the content I have: <table class="sortable table table-hover table-bordered"> <thead> <tr> <th>CPU</th> <th>Speed</th> <th>Cores</th> <th>TDP</th> <th> ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Utilizing Ionic to seamlessly integrate Firebase into a factory, maintaining separation of controllers and services within distinct files

I'm struggling with setting up a firebase factory for use in my controllers. Currently, this is how my code appears: index.html ... <!-- integrating firebase --> <script src="lib/firebase/firebase.js"></script> <script src="lib/ ...