ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Load Google Map into JQuery Dialog

Updated on July 1, 2016

In this article I will show you how to load a google map with a given address point into JQuery dialog box. You need few javascript references in order to load google map into Jquery dialog. Those are Google map API reference, JQuery Core library, JQuery UI reference on a static html page.

Create JQuery Dialog box

Create an empty html5 webpage and add the following jquery references. There are two ways to add Jquery reference. You can download JQuery and JQuery UI libraries into your working folder and refer them locally or you can find hosted libraries like google hosted libraries or code jquery. You can add following code into your html page had section just under title tag.

<!--Jquery core lib reference--->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!--Jquery UI style reference-->
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
    <!--JQuery UI lib reference-->
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>

Here I’m using the google library references. Now JQuery libraries are in place, lets add JQuery UI dialog. To trigger Jquery dialog I’m going to use a button. You can add following code snippet into your html page body.

<!--to trigger jquery dialog--->
    <input id="popMap" type="button" value="Map" />
    <!--the div that going to hold the map--->
    <div id="mapcanvas" style="display: none;">
    </div>

Now we can create a JQuery Dialog using following script. You need to add these code at the header below the script references.

<script type="text/javascript">
        $(document).ready(function () {
            //button click event handler
            $("#popMap").click(function () {
                $("#mapcanvas").dialog();
            });
        });
    </script>

Above code will generate a basic dialog box like below;

Now you can add some basic parameters to the Jquer dialog to make it look better and stable. Here I will be passing the height, width, a title and the modal status. So your modal dialog call will be changed as follows;

$("#mapcanvas").dialog({title:"Your Map Location",height:500,width:500,modal:true});

Now you will get an output as follows;

Setup Google Map API

Now your Jquery dialog box is ready to launch the google map with the desired address location. Lets add the following Javascript reference at the top of your page.

<!--Google Map API reference lib---->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>

Google Map API provides a very handy object called geocoder to manipulate google maps using javascript. This object expose a method called geocode(). This method accepts address parameter and returns the result status and the geometrical location. If the method call successful then you will get the exact location of the address and many details of it. You can use the following code to create a very simple google map and mark your address on it. So you can comment your JQuery dialog code and add this code below it;

var geocoder = new google.maps.Geocoder(); //create geocoder object
                // calling the geocode() function
                geocoder.geocode({ address: "3/46 Hunter Street Dubbo 2830 NSW" }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        //map option parameters
                        var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
                        //create map to draw address location
                        map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
                        // create the map point
                        var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });

                    }
                });

As you can notice I’m passing an address string and I’m checking the returned geocoderstatus, if it is OK then it is a success call. Next I’m using the result object location to create the map options parameter. Result object location contains the longitude and the latitude details of your given address. The other two parameters are the map type and the zoom number. Zoom number magnifies the map to the given size. Now you need to do a small css change to the map canvas div as follows;

<!--the div that going to hold the map--->
    <div id="mapcanvas" style="width:500px;height:500px;">
    </div>

Now save and refresh the page and click the map button you will get following output;

Now lets load the map into Jquery dialog. To do that you need to change the mapcanvas div styles as follows;

<!--the div that going to hold the map--->
    <div id="mapcanvas" style="display:none;">
    </div>
This will hide the div till it get loaded with the map. Now after loading the map into div we can call the dialog function inside the map api call like shown below;
var geocoder = new google.maps.Geocoder(); //create geocoder object
                // calling the geocode() function
                geocoder.geocode({ address: "3/46 Hunter Street Dubbo 2830 NSW" }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        //map option parameters
                        var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
                        //create map to draw address location
                        map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
                        // create the map point
                        var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
                        //calling the dialog
                        $("#mapcanvas").dialog({ title: "Your Map Location", height: 500, width: 500, modal: true });
                    }
                });

With the above code change, when user click on the map button it will first create a google map with the address point. After the map point mark you can call the Jquery Dialog. Then mapcanvas div will be loaded as a Jquery dialog box as shown below;

You can enhance the code a bit by adding a text box to give the address. Lets add a textbox to give any address location. Copy the following code snippet into your webpage;

<!--Textbox to input address---->
    <input id="txtAddress" type="text" placeholder="Type your Address here..." />

Now you need to make a small modification to the map API call. That is instead of using the address string will pass the text box user input as the address string. You can change your code as follows;

var geocoder = new google.maps.Geocoder(); //create geocoder object
                // calling the geocode() function
                geocoder.geocode({ address: $("#txtAddress").val() }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        //map option parameters
                        var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
                        //create map to draw address location
                        map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
                        // create the map point
                        var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
                        //calling the dialog
                        $("#mapcanvas").dialog({ title: "Your Map Location", height: 500, width: 500, modal: true });
                    }
                });

As you can notice now we are using the textbox address string not the static string. Save the code and refresh the page. You will get a page as follows;

You can check the live demo here

© 2014 wecode

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Yesudass 

      3 years ago

      Hi,

      There is an issue in this. If you click the button second time, The map becomes blank. Is there any solution for this issue ?

    • wecode profile imageAUTHOR

      wecode 

      3 years ago from Australia

      Have you include the modal dialog call into button event? if not put it then it will work, if you already added this must be happening in the second click ? let me know

    • profile image

      daryl 

      3 years ago

      it seems to be a problem when you click the button and it doesn't the show map anymore.

    • profile image

      Fathallah Wael 

      3 years ago

      $(document).ready(function () {

      //button click event handler

      $("#popMap").click(function () {

      $("#mapcanvas").dialog({ title: "Your Map Location", height: 500, width: 500, modal: true });

      var geocoder = new google.maps.Geocoder(); //create geocoder object

      // calling the geocode() function

      geocoder.geocode({ address: "3/46 Hunter Street Dubbo 2830 NSW" }, function (results, status) {

      if (status == google.maps.GeocoderStatus.OK) {

      //map option parameters

      var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };

      //create map to draw address location

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

      // create the map point

      var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });

      //calling the dialog

      }

      });

      });

      });

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)