Utilizing Google Maps on a jQuery Mobile website

I need to make a change on my jQuery mobile site that currently uses onload="initialize()" in the body tag to display a Google map. I want to find a way to show the map without needing onload="initialize()". Can someone help me figure out what modifications I need to make in the JavaScript code for this? site Link:

code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <title>test</title> 
<link rel="shortcut icon" href="http://computersforpeople.info/websites/images/favicon.ico">
<link rel="apple-touch-icon" sizes="72x72" href="http://computersforpeople.info/websites/Icons/apple-touch-icon-72x72.png"/>
    <link rel="apple-touch-icon" sizes="114x114" href="http://computersforpeople.info/websites/Icons/apple-touch-icon-114x114.png"/>
    <link rel="icon" type="image/png" href="http://computersforpeople.info/websites/Icons/icon48.png" />



<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://computersforpeople.info/websites/scripts/jquery-1.9.1.min.js"></script>
<script src="http://computersforpeople.info/websites/scripts/jquery.mobile-1.4.2.min.js"></script>  
<script type="text/javascript" src="http://computersforpeople.info/websites/scripts/jquery/lib/klass.min.js"></script>  
    <link href="http://computersforpeople.info/websites/scripts/jquery/photoswipe.css" type="text/css" rel="stylesheet" />

    <script type="text/javascript" src="http://computersforpeople.info/websites/scripts/jquery/code.photoswipe.jquery-3.0.4.min.js"></script>
    <script type="text/javascript" src="http://computersforpeople.info/websites/scripts/jquery/lib/klass.min.js"></script>
    <script type="text/javascript">
$( document ).ready(function() {
   $('a').live('click', function() {
      var $this = $(this);
      if ( !$this.attr('rel') || $this.attr('rel') != 'external' )
         $(document.getElementById( $this.attr('href') )).remove();
      });
});
</script>


<style type="text/css">
<!--
.style1 {font-size: large}
-->
</style>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> 
</script>
</head> 
<body style="margin:0px; padding:0px;">
<div data-role="page" data-add-back-btn="true" data-back-btn-text="Back" >
<div data-role="header" >
<h1>test</h1>
<div align="center"> 
</div>
</div>
     <ul  data-role="listview" data-inset="true" data-filter="false">
         <div data-role="collapsible-set" style="padding-left: 10px; padding-bottom: 10px;"> 
                <ul data-role="listview"  data-filter="false" id="test-more" >


   <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
 <script type="text/javascript"> 
 var geocoder;
  var map;
  var address ="6 Westbury Crescent Remuera NZ";
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 15,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    scrollwheel: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<b>'+address+'</b>',
                  size: new google.maps.Size(600,400)
                });

            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:address
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  } 
</script>

 <div data-role="collapsible" data-collapsed="false">
      <h3>Map</h3>
      <p> 
        <div align="center"><font size="2" color="#0000AA" face="Verdana, Arial, Helvetica, Sans-Serif"><b>
        <div id="map_canvas" style="width: 300px; height: 200px"></div>
        <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> 
</script> 
<script type="text/javascript"> 
_uacct = "UA-162157-1";
urchinTracker();
</script> 
        </b></font> 
        <font size="2" face="Arial, Helvetica, sans-serif">
        <br>
    <strong>Map location not guaranteed</strong> </font> </div>

         </p>
  </div>

</div>                        
    </ul> <br />
<li><a href="#contact_us" data-role="button" data-icon="info" data-iconpos="left" data-rel="dialog" data-transition="pop" id="contact">Contact Geoff Duncan</a></li>
</ul>


    </div>  


<div data-role="page" id="contact_us" data-title="Contact Us">
            <div data-role="header">
            <h1></h1>

            </div>

</body>
</html>

Answer №1

If you prefer not to rely on onload="initialize()" then you can manually call initialize() yourself. An example of this is using $(document).ready

$(document).ready(function () {
    initialize();
});

Your code has a few other issues that I have addressed and fixed. Here is a link to a fiddle showing your revised code: JSFiddle.net

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

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

What is the best way to show an image on the screen once a submit button is clicked?

I have a hidden loader-bar gif that I want to display when the user submits a form. Here is the code: <p class="loadingImg" style="display:none;"><img src="/design/styles/_shared/classic-loader.gif" alt="" /></p> Is there a way to ...

How can you merge one object with two different mongoose models?

Consider the scenario where I have two mongoose models set up: User Model Business Favorite Model Currently, I'm successfully retrieving the combined result if a user has any favorite businesses. However, I suspect that my current implementation mi ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Identifying a user's unique identity through a POST request using Node.js

Currently, I am developing a browser game that integrates voice communication. To capture audio within the browser, I have chosen to use wami-recorder. This tool relies on Flash technology to make a POST request to the server containing the recorded audio. ...

Experiencing problems with integrating Slim framework and AngularJS, such as encountering a 404 error

Although this may seem like a repeat question, I am encountering an issue with using AngularJS with Slim Framework web services. I have set up a webservice to retrieve a student record with a URL structure like: http://www.slim.local/api/getstudent/1 ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

Controller using the 'as' syntax fails to add new object to array

Lately, I've been experimenting with the Controller as syntax in Angular. However, I seem to be struggling to grasp its functionality. I am currently following a tutorial that utilizes $scope to bind the members of the controller function rather than ...

New to JavaScript and Bootstrap - eager to learn by using Bootstrap 4 Chart Template, just need help with a small issue in the code

I am eager to dive into Bootstrap 4 and data visualization charts. I want to replicate the visualizations found in the link below. However, after copying and pasting the code into Atom, it's not functioning as expected. I ensured that I copied the HT ...

Encountering a cannot POST / error while using Express

I am encountering an issue with my RESTful API while using Postman to call the route /websites. Despite my efforts, I keep receiving the error message "Cannot POST /websites". In addition, I am exploring the implementation of a job queue utilizing Express, ...

Having trouble with NextJS when trying to add an item to an element and render it in a Tailwind select

Struggling with displaying dynamic values in a select box using NextJS After fetching data from an API endpoint, I aim to populate a select box. However, my goal is to prepend a new element to the 'teams' array and ensure it appears first upon p ...

javascript doesn't execute the php script

Hello everyone, I've been working on a project for quite some time and I’ve encountered an issue that I can't seem to solve. Hopefully, you can help me out with this. I have a digital LED strip controlled by an Arduino, which in turn is control ...

What is the function of async in Next.js when triggered by an onClick

Need help with calling an async function pushData() from a button onClick event async function pushData() { alert("wee"); console.log("pushing data"); try { await query(` //SQL CODE `); console.log("Done&quo ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

Prevent any unauthorized modifications to the ID within the URL by implementing appropriate security measures

I am currently developing an application using React and Express. The URL structure is similar to this: /dashboard?matchID=2252309. Users should only have access to this specific URL, and modifying the match ID should not allow them to view the page. Is ...

Hyphens make Tablesorter sort numeric fields uniquely

I have a table where data is displayed in the format of YYYY-####. Sometimes, there are values like 2012-456 and 2012-1234. By default, the sorting places 2012-1234 before 2012-456. If I change the sort to 'numeric', it disrupts the order of othe ...

Ways to refine date results using JavaScript

Here is the JavaScript code I have: $(".datepicker").datepicker(); $(".datepicker-to").datepicker({ changeMonth: true, changeYear: true, maxDate: "0D" }); This code ensures that the date selected cannot be beyond the cur ...

Is it possible to retrieve the index of a particular element within an array during an update operation in MongoDB?

After executing the following update statement const result = await Post.updateOne({_id: postId},{ $pull: {reacts: {publisher: req.query.publisher}}, $inc: {postPoints: - reactsEnum[ReactType]} }); I am interested in obtaining the ...

Merge rxjs streams, identify modifications, and yield a single result

In the context of using Angular with .net Core WebApi, let's consider the development of a time management application designed to monitor task durations. The user initiates a task on the front end which triggers a timer displaying elapsed time. The ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...