Robot Framework - did not match any elements even in the firepath - xpath
I try to automate the CMS using robot framework, I got the XPath using firepath, I'm able to locate the element in Firefox, if I refresh the page, I couldn't locate the same XPath,I thought XPath got changed, but I got the same XPath when I try to get after page refresh,
IN SHORT again:
1) Got the Xpath, say "A"
2) Refresh the page
3) try to locate the element using "A".but it shows no element found
4) Get the new XPath, say "B"
5) Both A and B are same if I try now with A it works,
I need to automate this scenario, Thanks for your time.
I tried Frame too.
Note:
Every time after refresh element gets hidden until the click operation takes place.
<document>
<html style="height: 100%; overflow: hidden;">
<head>
**xpath**<body id="m_bodyElem" class="Gecko Gecko54 ENUS cms-bootstrap ui-layout-container" style="position: relative; height: 100%; overflow: hidden; margin: 0px; padding: 0px; border: medium none;">
<form id="aspnetForm" method="post" action="./CMSAdministration.aspx">
<div class="aspNetHidden">**xpath**
***
</document>
AFTER DOM ACTIVATION
<document>
<html>
<head>
<body id="m_bodyElem" class="Gecko Gecko54 ENUS cms-bootstrap">
<form id="aspnetForm" method="post" action="./UIPage.aspx?elementguid=a5568855-b030-47ff-801a-d524618a2ca7&displaytitle=false" onsubmit="if (window.Loader) { window.Loader.submitForm(1000, false); }; return true;">
<div class="aspNetHidden">
<script type="text/javascript"> //<![CDATA[ var theForm = document.forms['aspnetForm']; if (!theForm) { theForm = document.aspnetForm; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> </script>
<script src="/WebResource.axd?d=pynGkmcFUV13He1Qd6_TZBvGXq_vBGigUCFpfznup-OhZmSOTsQXuUy4Gn5GLidTPeGZMHkjMcSO21b0MZpf4w2&t=636160552680000000" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ function CloseDialog(refreshPage) { // Check that the document content has not been changed without saving. Stop closing the dialog when user decides to save the content. if (window.CheckChanges && !CheckChanges()) { return false; } if (typeof(refreshPage) === "undefined") { refreshPage = true; } try { // IE9 fix - wopener doesn't have to be available if(refreshPage && window.wopener && window.wopener.RefreshWOpener) { wopener.RefreshWOpener(window); } } catch(err) {} var canClose = true; if (window.onCloseDialog) { canClose = window.onCloseDialog(); } if (canClose) { if(top.closeDialog && (top != window)) { setTimeout(function(){ if(top && top.closeDialog && (top != window)){ top.closeDialog(window) } }, 1); } else { top.close(); } } return false; } //]]> </script>
<script type="text/javascript"> //<![CDATA[ function GetTop(){ if(top.getTop) { return top.getTop(window); } else { return top; } } //]]> </script>
<script src="/CMSPages/GetResource.ashx?scriptfile=%2fCMSScripts%2fUI%2fUIPage.js" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ function ToggleDiv(label){ var div = $cmsj(label).parent(); var image = div.find('.ToggleImage'); var hiddenField = image.next(); var affectedElements = div.find('.editing-form-category-caption').next(); if(hiddenField.val() == 'True') { div.removeClass('Collapsed'); hiddenField.val('False') image.attr('src', '/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2fCMSModules%2fCMS_PortalEngine%2fWebpartProperties%2fminus.png'); affectedElements.show(); } else { div.addClass('Collapsed'); hiddenField.val('True'); image.attr('src', '/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2fCMSModules%2fCMS_PortalEngine%2fWebpartProperties%2fplus.png'); affectedElements.hide(); } } //]]> </script>
<script type="text/javascript"> //<![CDATA[ function modalDialog(url, name, width, height, otherParams, noWopener, forceModal, forceNewWindow, setTitle) { // Header and footer is greater than before, increase window size accordingly if (typeof(height) === "number") { height += 66; } // Set default parameter values if (setTitle == undefined) { setTitle = true; } if (forceModal == undefined) { forceModal = true; } if (otherParams == undefined) { otherParams = 'toolbar=no,directories=no,menubar=no,modal=yes,dependent=yes,resizable=yes'; } var advanced = false; try { advanced = window.top.AdvancedModalDialogs; } catch (err) { } if (advanced && !forceNewWindow) { window.top.advancedModal(url, name, width, height, otherParams, noWopener, forceModal, setTitle, this); } else { var dHeight = height; var dWidth = width; if (width.toString().indexOf('%') != -1) { dWidth = Math.round(screen.width * parseInt(width, 10) / 100); } if (height.toString().indexOf('%') != -1) { dHeight = Math.round(screen.height * parseInt(height, 10) / 100); } var oWindow = window.open(url, name, 'width=' + dWidth + ',height=' + dHeight + ',' + otherParams); if (oWindow) { oWindow.opener = this; oWindow.focus(); } } } //]]> </script>
<script type="text/javascript"> //<![CDATA[ var applicationUrl = '/'; var imagesUrl = '/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2f'; var isRTL = false; //]]> </script>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fBootstrap%2fbootstrap.min.js" type="text/javascript"/>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fBootstrap%2fbootstrap.custom.js" type="text/javascript"/>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fControls%2fcontextmenu.js" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ menuSettings['cg0_motheractions'] = { activecss : 'unigrid-action-menuactive', inactivecss : '', activecssoffset : 0, button : 'Both', vertical : 'Bottom', offsetx : 0, offsety : 0, horizontal : 'Left', dynamic : false, mouseover : false, level : 0, rtl : false, up : false }; CM_Init('cg0_motheractions'); function ContextMenuAsyncCloser_cg0_motheractions(sender, args) { HideContextMenu('cg0_motheractions',true); } RegisterAsyncCloser(ContextMenuAsyncCloser_cg0_motheractions); //]]> </script>
<script type="text/javascript"> //<![CDATA[ function ContextExportObject(definition, backup) { var query = ''; if (backup) { query += '&backup=true'; } modalDialog(applicationUrl + 'CMSModules/ImportExport/Pages/ExportObject.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1] + query, 'ExportObject', 750, 230); } function ContextRestoreObject(definition, backup) { var query = '&ug=UG_m_c_plc_lt_ctl01_ST_UI_Listing_gridElem'; if (backup) { query += '&backup=true'; } modalDialog(applicationUrl + 'CMSModules/ImportExport/Pages/RestoreObject.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1] + query, 'RestoreObject', 750, 400); } function ContextCloneObject(definition) { modalDialog(applicationUrl + 'CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1], 'CloneObject', 750, 470); } //]]> </script>
<script type="text/javascript"> //<![CDATA[ menuSettings['cg0_mActions'] = { activecss : 'unigrid-menu-panel', inactivecss : 'unigrid-menu-panel', activecssoffset : 0, button : 'Both', vertical : 'Bottom', offsetx : 0, offsety : 0, horizontal : 'Left', dynamic : false, mouseover : false, level : 0, rtl : false, up : false }; CM_Init('cg0_mActions'); function ContextMenuAsyncCloser_cg0_mActions(sender, args) { HideContextMenu('cg0_mActions',true); } RegisterAsyncCloser(ContextMenuAsyncCloser_cg0_mActions); //]]> </script>
<script src="/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fjquery%2fjquery-dialog.js" type="text/javascript"/>
<script src="/ScriptResource.axd?d=x6wALODbMJK5e0eRC_p1LReXSSMeIyuHkoW0S0JbeJThyUVM1Ht4tiF1s3IQMCFhPQK_xpltR2WGldkDgz-jn22orun3s0371LlvE1PAZKjo6kObtvOl-fuKz6i7Aya00&t=7c776dc1" type="text/javascript"/>
<script src="/ScriptResource.axd?d=P5lTttoqSeZXoYRLQMIScL2FKbXixpOQbTl1EIUzR5PmuwyrWWddMW5IgYL1QiI9_cn_1H5B6OyKNQvmWuhRMgoFqxMQlu84DtMU2tQiSt_N7pheWxn0ZjjBaQY6SWz90&t=7c776dc1" type="text/javascript"/>
<script type="text/javascript"> //<![CDATA[ var CMS = CMS || {}; CMS.Application = { "applicationName": "PIM", "imagesUrl": "/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2f", "isDebuggingEnabled": false, "contexthelp": { "contextHelp": { "application": { "description": null, "helpTopics": [] }, "helpTopics": [] }, "suppressContextHelp": false }, "applicationUrl": "/", "isDialog": false, "isRTL": "false" }; //]]> </script>
<div class="aspNetHidden">
<script type="text/javascript"> //<![CDATA[ Sys.WebForms.PageRequestManager._initialize('m$manScript', 'aspnetForm', ['tm$c$plc$lt$ctl00$HeaderActions$headerElem$pnlUp','','tm$c$plc$lt$ctl01$ST_UI_Listing$gridElem$a$pnlUpdate','','tm$c$ctxM','','tm$pM$pMP','','tm$c$plc$lt$ctl01$MessagesPlaceholder$plcMess$pMP','','tm$c$plc$lt$ctl01$ST_UI_Listing$gridElem$plcMess$pMP',''], [], [], 90, 'm'); //]]> </script>
<div id="m_pnlBody" class="PageBody">
<div id="m_pM_pMP"/>
<div id="m_c_m"/>
<div id="m_c_ctxM">
<div id="UIHeader" class="UIHeader">
<div id="m_c_plc_lt_ctl00_HeaderActions_headerElem_pnlUp">
<div id="m_c_plc_lt_ctl00_HeaderActions_headerElem_pnlActions" class="header-actions-container">
<button id="m_c_plc_lt_ctl00_HeaderActions_headerElem_headerElem_HA_0" class="btn btn-primary" type="button" name="m$c$plc$lt$ctl00$HeaderActions$headerElem$headerElem_HA_0" value="New Product Type" onclick="window.open('/CMSModules/AdminControls/Pages/UIPage.aspx?elementguid=6e43429b-1086-4669-8130-9ee24ebb1d21&displaytitle=false','_self'); return false;__doPostBack('m$c$plc$lt$ctl00$HeaderActions$headerElem$headerElem_HA_0','')">New Product Type</button>
</div>
<div id="m_c_plc_lt_ctl00_HeaderActions_headerElem_pnlAdditionalControls" class="dont-check-changes "/>
</div>
<div id="m_c_plc_lt_ctl00_HeaderActions_HeaderActions_zone_PageTitle_pnlHeader" class="PageHeader SimpleHeader">
<div id="CMSHeaderDiv" class="CMSHeaderDiv"/>
<div id="CKToolbar" class="CKToolbar"/>
</div>
<div id="UIContent" class="UIContent scroll-area" style="height: auto; top: 56px; bottom: 0px;">
</div>
<script type="text/javascript"> //<![CDATA[ (function() {var fn = function() {$get("m_manScript_HiddenField").value = '';Sys.Application.remove_init(fn);};Sys.Application.add_init(fn);})();//]]> </script>
<script type="text/javascript"> //<![CDATA[ document.pageLoaded = true; //]]> </script>
<script type="text/javascript"> //<![CDATA[ cmsrequire(['CMS/UniGrid'], function(module) { new module({ "id": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem", "uniqueId": "m$c$plc$lt$ctl01$ST_UI_Listing$gridElem", "hdnCmdNameId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidCmdName", "hdnCmdArgId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidCmdArg", "hdnSelHashId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidSelectionHash", "hdnSelId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_hidSelection", "gridId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_v", "resetSelection": false, "allowSorting": false }); }); //]]> </script>
<script type="text/javascript"> //<![CDATA[ cmsrequire(['CMS/AdvancedExport'], function(module) { new module({ "id": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a", "uniqueId": "m$c$plc$lt$ctl01$ST_UI_Listing$gridElem$a", "unigridId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem", "hdnParamId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_hdnParameter", "btnFullPostbackUniqueId": "m$c$plc$lt$ctl01$ST_UI_Listing$gridElem$a$btnFullPostback", "chlColumnsId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_chlColumns", "hdnDefaultSelectionId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_hdnDefaultSelection", "revRecordsId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_revRecords", "cvColumnsId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_cvColumns", "mdlAdvancedExportId": "m_c_plc_lt_ctl01_ST_UI_Listing_gridElem_a_mdlAdvancedExport", "fixHeight": false, "alertMessage": null }); }); //]]> </script>
The button I need to interact is
//button[#id='m_c_plc_lt_ctl00_HeaderActions_headerElem_headerElem_HA_0']
Related
return isTrusted false
I'm writing my first web component with Stencil. It's a pills component published here : https://github.com/reservoir-dogs/rp-pills The component code's : import { Component, Prop, Watch, Event, EventEmitter } from '#stencil/core'; #Component({ tag: 'rp-pills', styleUrl: 'rp-pills.scss', shadow: false }) export class RpPills { #Prop() items: any[] = []; #Prop() displayProperty: string; #Prop({ mutable: true }) value: any; #Prop() class: string; #Prop() theme: string = 'default'; #Prop() emptyMessage: string = 'No item'; classes: string; #Event() valueChange: EventEmitter; onClick(item: any) { this.value = item; this.valueChange.emit(this.value); } #Watch('class') #Watch('theme') watchHandler() { this.classes = `nav nav-pills ${this.theme} ${this.class}`; } render() { if (this.items.length > 0) return ( <ul class={this.classes}> {this.items.map((item) => <li onClick={() => this.onClick(item)} class={this.value === item ? 'active' : ''} > <a>{item[this.displayProperty]}</a> </li>)} </ul> ); else return ( <ul class={this.classes}> <li class="empty"> <a>{this.emptyMessage}</a> </li> </ul> ); } } This test work fine : it('should work with a list of items and selected item', async () => { const cmp = new RpPills(); cmp.valueChange = { emit: () => { } }; const spy = jest.spyOn(cmp.valueChange, 'emit'); cmp.onClick({name:'Coucou'}); expect(spy).toHaveBeenCalledWith({ name: 'Coucou' }); }); But my HTML sample and an integration in Ionic App does not work and return the following message : {"isTrusted":false} HTML sample : <!DOCTYPE html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0"> <title>Stencil Component Starter</title> <script src="/build/rppills.js"></script> </head> <style> .orange .active a { background-color: #ff0000; } .orange a { background-color: #ff6a00; } div { float: left; clear: both; } </style> <body> <div> <rp-pills display-property="name" class="nav-pills-bordered" theme="orange"> </rp-pills> <span></span> </div> <div> <rp-pills display-property="name" class="nav-justified"> </rp-pills> <span></span> </div> <div> <rp-pills display-property="name" class="nav-pills-bordered nav-justified"> </rp-pills> <span></span> </div> <div> <rp-pills class="nav-pills-bordered"> </rp-pills> <span></span> </div> <div> <rp-pills empty-message="Aucun message" class="nav-pills-bordered"> </rp-pills> <span></span> </div> <div> <rp-pills> </rp-pills> <span></span> </div> <script> var cmps = document.querySelectorAll('rp-pills'); for (var i = 0; i < cmps.length; i++) { var cmp = cmps[i]; if (cmp.attributes.length > 0 && cmp.attributes[0].name == 'display-property') { cmp.value = { 'name': 'Coucou' }; cmp.items = [cmp.value, { 'name': 'Comment ca va ?' }, { 'name': 'Au revoir' }]; cmp.addEventListener('valueChange', (event) => { alert(JSON.stringify(event)); }); } } setInterval(() => { var cmps = document.querySelectorAll('rp-pills'); var spans = document.querySelectorAll('span'); for (var i = 0; i < cmps.length; i++) { if (cmps[i].value != undefined) spans[i].innerText = cmps[i].value.name; } }, 1000); </script> </body> </html>
2 errors I tried to do that : <rp-pills [items]="jeux" [(value)]="partie.jeu"></rp-pills> The event of my Stencil component's : is not compliant with angular two-way binding contain a property 'detail' where there is my value Use in Ionic App HTML code <rp-pills [items]="jeux" [value]="partie.jeu" (valueChange)="jeuChange($event.detail)"></rp-pills> TypeScript code jeuChange(jeu: Jeu) { this.partie.jeu = jeu; }
i need to hide a dynamically created div using dynamically created button using jquery constructor function
<!DOCTYPE html> <html> <head> <script src='jquery-1.11.2.js' type="text/javascript"></script> <div id='divn'></div> <script> function createDomControls(id,appendToId) { this.id=id; this.appendToId=appendToId; this.divTag=function(divId,className,style,appendToId) { //var divId = "div" + Math.floor((Math.random() * 100000) + 1); $('<div/>', { id: divId, style: style, class:className }).appendTo('#' + appendToId); } this.buttonTag=function(type,id,value,appendToId) { $('<input/>',{ type:type, id:id, value:value, onclick:onclick function(){ $('#div1').hide(); } }); } } var domControls=new createDomControls('divm','divn'); var div=domControls.divTag('div1','cls','background:pink;width:500px;height:670px;padding:12px;margin:0px;','divn'); var btn=domControls.buttonTag('button','btn1','+','div1'); </script> </head>
Google Maps current location JavaScript error
I want to get my current location using Google Maps Geolocation by Latitude and Longitude and I also want to set the origin as my current location but I'm not getting the current location. What should I do? This is my code: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Draggable directions</title> <style> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script> <script> var rendererOptions = { draggable: true }; var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); var directionsService = new google.maps.DirectionsService(); var map; function initialize() { var lat, lon, mapOptions; if(navigator.geolocation){ navigator.geolocation.getCurrentPosition( function(position){ lat = position.coords.latitude; lon = position.coords.longitude; mapOptions = { zoom: 7, center: new google.maps.LatLng(lat, lon), }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById('directionsPanel')); google.maps.event.addListener(directionsDisplay, 'directions_changed', function() { computeTotalDistance(directionsDisplay.getDirections()); }); calcRoute(); }, function(error){ alert('ouch'); }); } else { alert("Your browser doesn't support geolocations, please consider downloading Google Chrome"); } } function calcRoute() { var request = { origin: new google.maps.LatLng(lat, lon), destination: new google.maps.LatLng(10.5200,76.2100), travelMode: google.maps.TravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } function computeTotalDistance(result) { var total = 0; var myroute = result.routes[0]; for (var i = 0; i < myroute.legs.length; i++) { total += myroute.legs[i].distance.value; } total = total / 1000.0; document.getElementById('total').innerHTML = total + ' km'; } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas" style="float:left;width:70%; height:100%"></div> <div id="directionsPanel" style="float:right;width:30%;height 100%"> <p>Total Distance: <span id="total"></span></p> </div> </body> </html>
JVectorMap - Selecting a Region Using a Button
I am using J Vector Map (http://jvectormap.com/documentation/javascript-api/) to create a map of the United States. What I want to be able to do is have a button for each state that you can click on and have the corresponding region in the map be selected (or unselected, if it already was selected). I am trying to use map.setSelectedRegion for this, but I can't get any of the code to work. Currently trying map.setSelectedRegion("US-CA") to no avail. Any ideas on what to do? Thanks!
There seem to be a lot of request for linking links with jvectormap. I've put together a jsfiddle here: http://jsfiddle.net/3xZ28/117/ HTML <ul id="countries"> <li>Romania</li> <li>Australia</li> </ul> <div id="world-map" style="width: 600px; height: 400px"></div> JS var wrld = { map: 'world_mill_en', regionStyle: { hover: { "fill": 'red' } } }; function findRegion(robj, rname) { var code = ''; $.each(robj, function (key) { if ( unescape(encodeURIComponent(robj[key].config.name)) === unescape(encodeURIComponent(rname)) ) { code = key; }; }); return code; }; $(document).ready(function () { $('#world-map').vectorMap(wrld); var mapObj = $('#world-map').vectorMap('get', 'mapObject'); $('#countries').on('mouseover mouseout', 'a:first-child', function (event) { // event.preventDefault(); var elem = event.target, evtype = event.type, cntrycode = findRegion(mapObj.regions, $(elem).text()); if (evtype === 'mouseover') { mapObj.regions[cntrycode].element.setHovered(true); } else { mapObj.regions[cntrycode].element.setHovered(false); }; }); });
Once you've set the handle var mapObject = $('#your_map_div_id').vectorMap('get', 'mapObject'); Just use the built in function setSelectedRegions (mind the "s"): mapObject.setSelectedRegions(your_region_code); //to set mapObject.setSelectedRegions({your_region_code:false}); //to unset If it still doesn't work, post your code, maybe it's something else.
This code is outdated, below is updated version of the code, according jvectormap latest API. Here is demo snippet: <!DOCTYPE html> <html> <head> <title>jVectorMap demo</title> <link rel="stylesheet" href="jqvmap.min.css" type="text/css" media="screen"/> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="jquery.vmap.min.js"></script> <script src="jquery.vmap.world.js"></script> <script> jQuery(document).ready(function () { $('#vmap').vectorMap({ map: 'world_en', backgroundColor: '#2f95c9', color: '#ffffff', hoverOpacity: 0.7, selectedColor: '#666666', enableZoom: true, showTooltip: true, scaleColors: ['#C8EEFF', '#006491'], normalizeFunction: 'polynomial', regionsSelectableOne: false, regionsSelectable: false, series: { regions: [{ scale: ['#C8EEFF', '#0071A4'], normalizeFunction: 'polynomial' }] } }); var mapObj = $('#vmap').data('mapObject'); $('#countries').on('mouseover mouseout', 'a:first-child', function (event) { // event.preventDefault(); var elem = event.target, evtype = event.type; if (evtype === 'mouseover') { mapObj.select($(elem).attr('id')); } else { mapObj.deselect($(elem).attr('id')); }; }); }); </script> </head> <body> <ul id="countries"> <li><a id="RO" href="">Romania</a></li> <li><a id="AU" href="">Australia</a></li> </ul> <div id="vmap" style="width: 100vw; height: 100vh;"></div> </body> </html>
Adding Multiple Markers to Google Maps v3 from JSON
I've been trying to make a web app that shows multiple markers on google maps. I tried using this tutorial and the code works fine until I get to the point where I need to get the JSON data from the server instead of using the example JSON data in the same js file as the code. I try to save the ajax response into variable but i get this error TypeError: json is null [Break On This Error] for (var i = 0, length = json.length; i < length; i++) { And this is the code I am using. <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map-canvas { height: 100% } </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script> </script> <script type="text/javascript"> function initialize() { var mapOptions = { center: new google.maps.LatLng(57.9, 14.6), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); var json = (function () { var json = null; $.ajax({ 'async': false, 'global': false, 'url': "http://myurl.com/getdata", 'dataType': "json", 'success': function (data) { json = data; } }); return json;})(); for (var i = 0, length = json.length; i < length; i++) { var data = json[i], latLng = new google.maps.LatLng(data.lat, data.lng); // Creating a marker and putting it on the map var marker = new google.maps.Marker({ position: latLng, map: map, title: data.title }); } var infoWindow = new google.maps.InfoWindow(); // Attaching a click event to the current marker google.maps.event.addListener(marker, "click", function(e) { infoWindow.setContent(data.description); infoWindow.open(map, marker); }); // Creating a closure to retain the correct data //Note how I pass the current data in the loop into the closure (marker, data) (function(marker, data) { // Attaching a click event to the current marker google.maps.event.addListener(marker, "click", function(e) { infoWindow.setContent(data.description); infoWindow.open(map, marker); }); })(marker, data); } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas"/> </body> </html>