Is there a way to extract variables from a MySQL database and integrate them into a JavaScript function?

Hello everyone, I am looking to add markers on a map. In order to do this, I need to extract longitude and latitude from a database table.

1- I have used JavaScript to display the map (Google Maps).

    var map;
var initialize;

initialize = function(){
  var latLng = new google.maps.LatLng(x,y); 
  var myOptions = {
    zoom      : 14, 
    center    : latLng, 
    mapTypeId : google.maps.MapTypeId.TERRAIN,
    maxZoom   : 20
  };

  map      = new google.maps.Map(document.getElementById('map'), myOptions);

  var marker = new google.maps.Marker({
    position : latLng,
    map      : map,
    title    : "sousse"
    //icon     : "marker_sousse.gif" 
  });

2- I retrieve Longitude and Latitude from the database and store them in two String Lists using Java:

package beans;

import .
.
.
.
.


@ManagedBean(name = "js")
@RequestScoped
public class Map {
    ArrayList<String> Listlat = new ArrayList<String>();
    ArrayList<String> Listlng = new ArrayList<String>();
    GestionAnalyseLocal m;
    ResultSet resultSet;

    public Map() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/pfedb", "root", "");
            Statement statement = connect.createStatement();
            resultSet = statement.executeQuery("select * from t_analyse");
        } catch (Exception e) {
            System.out.println("erreur" + e);
            e.printStackTrace();
        }

    }
    public ArrayList<String> ExtractLat(ResultSet rs) {
        try {
            while (rs.next()) {
                Listlat.add(rs.getString("latitude"));

            }
        } catch (Exception e) {
            System.out.println("erreur" + e);
            e.printStackTrace();
        }
        return Listlat;
    }

    public ArrayList<String> ExtractLng(ResultSet rs) {
        try {
            while (rs.next()) {
                Listlng.add(rs.getString("Longitude"));

            }
        } catch (Exception e) {
            System.out.println("erreur" + e);
            e.printStackTrace();
        }
        return Listlng;
    }
}

3- Now, I am trying to find a solution to replace the x and y in the js function with the two lists... Here is the HTML page:

    <!DOCTYPE html> 
<html >
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:jsf="http://xmlns.jcp.org/jsf"
    xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
    xmlns:p="http://primefaces.org/ui"
    template="/WEB-INF/template/template.xhtml"
    >
    <ui:define name="title">Map</ui:define>
   <ui:define name="content">

  <head>


    <link rel="stylesheet" href="jquery-ui-1.8.12.custom.css" type="text/css" /> 
  </head>
  <style type="text/css">
    #container{position:relative;width:990px;margin:auto;}
    #container #map{width:500px;height:500px;margin:auto;}
  </style>
  <body>
    <div  id="container">
        <div id="map">
            <p>Please wait while the map is loading...</p>
        </div>
    </div>

    <!-- Include Javascript -->

    <script type="text/javascript" src="resources/js/jquery.min.js"></script>
    <script type="text/javascript" src="resources/js/jquery-ui-1.8.12.custom.min.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="resources/js/functions.js"></script>

  </body>
  </ui:define>
  </ui:composition>
</html>

Note: I am not very familiar with JavaScript. :(

Answer â„–1

If you're looking to easily retrieve latitude and longitude using jQuery and AJAX, consider creating a method that can return both values simultaneously.

$(document).ready(function(evt){
    $.get('/url/to/get/coords', function(response){
        initialize(response.longitude, response.latitude);
    });
});

Make sure the new method returns data in JSON format and adjust your initialize function accordingly:

initialize = function(x,y){ your code }

This way, you can pass the coordinates seamlessly. Hope this explanation helps!

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 Establishing a Connection to WCF Service using Ionic Project and AngularJS

Greetings, I am currently experiencing an issue tasked with connecting my Ionic project to a WCF service located on another PC (running a C# Application) within the local network. I have verified that the network connection between the PCs is functioning p ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...

Pattern: locate a sequence of three numerical digits within the provided whole number

As I am relatively new to Regexp, my current method involves using Regexp along with a loop: boolean match = false; int number = 0; String Str1 = String.valueOf(451999277); for (int i=0;match == false;i++) { //check the pattern through loop matc ...

The mobile screen size shortcuts are malfunctioning, while the regular links are functioning properly

ISSUE: Links in alias buttons are not working on mobile screen size, while normal links to other webpages like social media work fine. Description I created a project using an HTML, CSS, JS building tool from The project was exported and placed into a ...

Struggling with transferring information from JavaScript to PHP through the use of Ajax

Currently, I am working on creating a string using a JavaScript function and then passing it to PHP. This is the block of code in my JavaScript file: <script> function passVal(){ var strUrl = buildStringUrl(lat1, lng1, lat2, ...

interactive vuetify navigation trail elements

Currently working on a vuetify project and I'm facing an issue with implementing breadcrumbs. The problem arises when clicking on a breadcrumb, as it deletes the ones that come after it in the list. I've tried some code snippets but could only ma ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...

Launch the Chrome browser with just one line of code: `WebDriver driver = new ChromeDriver()`

Is it possible to start the Chrome browser by simply using the code WebDriver driver = new ChromeDriver(); without specifying the chromedriver.exe path? To try this, I added the path for chromedriver.exe in System Properties>>Environment Variabl ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Is there a way to determine if an npm package is compatible with ES6 import syntax for importing?

Aside from reviewing the documentation of the package and trying different methods through trial and error, how can one be certain if an npm package can be imported using the ES6 import syntax? Is there a specific file within the package folder that can b ...

Data that has been encrypted is not being properly added to the MySQL database table

I am currently in the process of transitioning my encryption methods from des to blowfish. Here is the function I am using for encryption and decryption: function NewCryptStr($EncryptOrDecrypt,$Str) { $Key='test'; $IVSize=mcrypt_get_iv_size ...

How can I ensure that images display properly when exporting charts to HTML and opening them in an application? Is there a way to set an

My goal is to convert a jrxml file with a chart into html format. I then want to read the generated html file and include the chart in an email. However, I've encountered an issue when exporting the report to html: the image source looks like this ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...

Personalize the appearance of your stackLabels in Highcharts with dynamic customization options

I recently created a bar graph using Highcharts. You can check it out here: http://jsfiddle.net/v1rbz41q/3/ Here's the code snippet I used: chartw.yAxis [0] .options.stackLabels.formatter = function () {              return "werfdc";   ...

When attempting to save a model instance in Django that includes `auto_now_add`, an error message may be generated stating "Column 'xxx' cannot be null."

I'm feeling lost with this error that keeps popping up. Let's take a look at the Location object I have: class Location(models.Model): class Meta: db_table = 'location' location_id = models.UUIDField(primary_key=True, ...

Error: Unable to simplify version range

Attempting to follow the Express beginner's guide. I created an app and executed npm install as per the provided instructions. > npx express-generator --view=pug myapp > npm install npm ERR! semver.simplifyRange is not a function npm ERR! A com ...

Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how ...

Using React Native's stylesheet to apply multiple values in a CSS statement

Here's a scenario to help clarify my question: Imagine I want to add margin to an element in the following way: const myView = () => <View style={styles.viewStyle}></View> const styles = StyleSheet.create({ viewStyle: { margin: ...

Configuration Error: Pre-Test Setup Failed

An error message appeared stating that there was a failed connection to the binary FirefoxBinary located at C:\Program Files\Mozilla Firefox\firefox.exe on port 7055. The process output included various logs related to addons and blocklists. ...

Is it not possible to utilize async/await with MongoDB Model, despite it yielding a Promise?

Currently, I am facing an issue with a function in my code that is supposed to retrieve a user's inventory and then fetch the price property of each element using data from a Price Collection. Below is a snippet of the function (not the entire thing, ...