Google Maps current location JavaScript error - google-geolocation

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>

Related

Robot Framework - did not match any elements even in the firepath

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']

Want to highlight/change color of certain words in Ace Editor?

I am setting text using the following:
var someString = 'Mark has solved the problem';
editor.getSession().setValue(someString);
In above case, Need only 'Mark' to appear in blue color.
Is there a way to load html tags in ace editor or manipulate styling of certain words?
You can create custom highlight rules to do this
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<meta charset="utf-8">
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.ace_customTokenName {color: darkred}
</style>
</head>
<body>
<div id="editor" style="height: 500px; width: 800px"></div>
<script src="https://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<script>
define('ace/mode/custom', [], function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var CustomHighlightRules = require("ace/mode/custom_highlight_rules").CustomHighlightRules;
var Mode = function() {
this.HighlightRules = CustomHighlightRules;
};
oop.inherits(Mode, TextMode);
(function() {
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/custom_highlight_rules', [], function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var CustomHighlightRules = function() {
var keywordMapper = this.createKeywordMapper({
"variable.language": "this",
"keyword": "Mark|Ben|Bill",
"constant.language": "true|false|null",
// it is also possible to use css, but that may conflict with themes
"customTokenName": "problem"
}, "text", true);
this.$rules = {
"start": [
{
regex: "\\w+\\b",
token: keywordMapper
},
]
};
this.normalizeRules()
};
oop.inherits(CustomHighlightRules, TextHighlightRules);
exports.CustomHighlightRules = CustomHighlightRules;
});
var editor = ace.edit("editor");
editor.session.setMode("ace/mode/custom");
var someString = 'Mark has solved the problem';
editor.session.setValue(someString);
</script>
</body>
</html>

OpenLayers: Geocoding Data Google + OSM

I got this error TypeError: placemarks is undefined I use google api and openlayer api .
help me this. I am using google api v3 and openLayer map i want to give address in textbox and click button and the geocoding perform.
In my code I got this error TypeError: placemarks is undefined Here is my full code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>OpenLayers: Geocoding Data Google + OSM</title>
<link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=AIzaSyBz7CjlxpWO8HgM_ATuq3_F85wfAoupXck&language=de"></script>
<script src="OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js" type="text/javascript"></script>
<style type="text/css">
#map {
width: 100%;
height: 80%;
border: 1px solid black;
}
</style>
<script type="text/javascript">
var map, vectors, geocoder;
// Define marker style
// #fixme: where can we get information about these marker styles
var markerStyle = {
externalGraphic : 'img/marker.png',
pointRadius : 12
};
function init() {
// Add the map
var options = {
projection : new OpenLayers.Projection("EPSG:900913"),
displayProjection : new OpenLayers.Projection("EPSG:4326"),
units : "m",
maxResolution : 156543.0339,
maxExtent : new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
};
map = new OpenLayers.Map('map', options);
// Add the OpenStreetMaps Layer
var osm = new OpenLayers.Layer.OSM.Mapnik("OpenStreetMap (Mapnik)", {
displayOutsideMaxExtent : true,
wrapDateLine : true,
buffer : 0
});
map.addLayer(osm);
// Add the google maps Layer
var gmap = new OpenLayers.Layer.Google("Google", {
sphericalMercator : true
});
map.addLayer(gmap);
// Add a vector Layer which holds the markers
vectors = new OpenLayers.Layer.Vector("Vector Layer");
map.addLayer(vectors);
// Allow marker drag
var dragCtl = new OpenLayers.Control.DragFeature(vectors);
dragCtl.onComplete = function(feature, position) {
var ll = map.getLonLatFromPixel(position);
var coords = ll.transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
alert('New coordinates: ' + coords.lon + ' ' + coords.lat);
}
map.addControl(dragCtl);
dragCtl.activate();
map.addControl(new OpenLayers.Control.LayerSwitcher());
// Center map
var centerLonLat = new OpenLayers.LonLat(10.5, 51.6).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter(centerLonLat, 5);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address' : address
}, gotGeocodes);
alert("hiiii");
}
function gotGeocodes(response) {
// Clear markers from vector layer
alert("hi");
vectors.destroyFeatures();
if (typeof response.location !== 'undefined') {
alert("Sorry, we were unable to geocode that address");
} else {
var placemarks = response.Placemark;
// We may get more than one result here. So you can display
// all results or just the first like here
if (placemarks.length > 0) {
var coords = placemarks[0].Point.coordinates;
var ll = new OpenLayers.LonLat(coords[0], coords[1]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var pointGeometry = new OpenLayers.Geometry.Point(ll.lon, ll.lat);
var point = new OpenLayers.Feature.Vector(pointGeometry, null, markerStyle);
vectors.addFeatures([point]);
map.setCenter(ll, 16);
}
}
}
</script>
</head>
<body onload="init();">
<h1 id="title">Get geocoding data from google</h1>
<p id="shortdesc">
Get geocoding data from google an show it in openstreetmap or google maps.
</p>
<form action="#" onsubmit="codeAddress(); return false;">
<strong>Enter an address:</strong>
<input type="text" id="address" name="q" value="" size="40" />
<input type="submit" name="find" value="Search" />
</form>
<div id="map"></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>

Resources