Adding a push pin to a map using Javascript - javascript

How will I be able to put a pin using a click of my mouse? given this is the code:
function AddPushpin()
{
var shape = new VEShape(VEShapeType.Pushpin, **map.GetCenter()**);
shape.SetTitle('sample');
shape.SetDescription('This is shape number '+pinid);
pinid++;
map.AddShape(shape);
}
it's pointing to the center..
do you have any idea on how to add an image to the pushpin hover?

Here's an example that adds a pushpin during the OnClick event of the Map, and sets the Shape's Photo URL to display an image within the InfoxBox.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&mkt=en-US"></script>
<script type="text/javascript">
var map = null;
function GetMap()
{
map = new VEMap("myMap");
map.LoadMap();
// Attach the OnClick event
map.AttachEvent("onclick", OnClick_Handler);
// You could Dettach the OnClick event like this
//map.DetachEvent("onclick", OnClick_Handler);
}
function OnClick_Handler(e){
// "sender" is the VEMap that raised the event
// "e" is the VE Map Event Object
// Get the Lat/Long where the Mouse was clicked
var pushpinLocation = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
// Create the Pushpin Shape
var s = new VEShape(VEShapeType.Pushpin, pushpinLocation);
s.SetTitle("test pushpin");
s.SetDescription("test description");
s.SetPhotoURL("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png");
// Plot a Shape at the Clicked location
map.AddShape(s);
}
</script>
</head>
<body onload="GetMap();">
<div id='myMap' style="position:relative; width:400px; height:400px;"></div>
</body>
</html>

check out this article...
function InitMap ()
{
// add code to init your map....
// attach the onclick event...
map.AttachEvent("onclick", MouseClick);
}
function MouseClick(e)
{
map.AddPushpin('pin',
e.view.latlong.latitude,
e.view.latlong.longitude,
88,
34,
'pin',
'MyPin',
1);
}

Related

Using Raphaël from a jQuery call

I'm trying to create a simple application for drawing a graph based on user input. I'm using Raphaël and jQuery. I'd like to have the user give their input on a form, and then draw the SVG graphic. The problem I'm having is that when I call the draw function from within a jQuery click event, the SVG object flickers and then disappears. There's a MWE below. (Perhaps it could be more minimal.) How can I make sure that the graphic stays there after the button click?
<!doctype html>
<html>
<head>
<title>Example</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery-ui-1.10.4/jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4/ui/jquery-ui.js"></script>
<link rel="stylesheet" href="jquery-ui-1.10.4/themes/base/jquery-ui.css" />
<script type="text/javascript" src="raphael-min.js"></script>
</head>
<body>
<form>
<button id="generate-button">Generate</button>
</form>
<div id="canvas"/>
<script>
function CustomObject() {
this.draw = function() {
// Creates canvas 320 × 200 at 10, 50
paper = Raphael("canvas", 100, 100 );
boundary = window.paper.rect( 5, 5, 25, 25 );
boundary.attr("stroke-dasharray" , "--" );
// Creates circle at x = 50, y = 40, with radius 10
circle = paper.circle(50, 40, 10);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff");
}
}
var plot = new CustomObject();
// plot.draw(); // if I call it here, the scene is drawn "normally"
$( "#generate-button" )
.button()
.click(function() {
plot.draw(); // when I call it here, the SVG flickers and disappears
});
</script>
</body>
</html>
The default type for a button is submit and when inside a form will try to submit the form.
Your click handler is executing and then submitting the form which is causing the flicker.
Either take the button out of the form or return false from the click event handler as this will disable the browsers default action.

Here.com (Nokia Api for Maps) : How to manage circles with changing colors on click?

I'm using the Nokia API for my web app (Javascript), and I draw circles in my map with different radium. The thing is when I zoom in, the circle has the same size, which means that when I zoom in, there's a level where I can't see anything else since it covers the whole map. Hence, I want the circle to keep the same size even if I zoom in.
For that, I tried SVG Markers, which solve this problem, but the thing is I had to program when I click on one of them, the color has to change (it's all a mess, and it reduces the performance of the app).
If anyone can help me, that would be awesome !
There are three key points which need to be answered to find a solution your question.
To add functionality when a marker is clicked, you need to add a listener to the click event i.e. marker.addListener("click", function (evt) { ...etc
To switch the color of an SVG marker you need two separate icons for that marker. The icon property is immutable, and hence it should only be updated using the set() method i.e. marker.set("icon", markerIcon);
To force a refresh of the screen after the new icon has been set you need to update the map display - map.update(-1, 0);
Combining these points togther there is a working example appended below. You need to substitute in your own app id and token to get it to work of course.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<title>Highlighing a marker: Istanbul (Not Constantinople)</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script language="javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<p> Click on the marker to change it.</p>
<div id="gmapcanvas" style="width:600px; height:600px;" > </div><br/><br/>
<script type="text/javascript">
// <![CDATA[
/////////////////////////////////////////////////////////////////////////////////////
// Don't forget to set your API credentials
//
// Replace with your appId and token which you can obtain when you
// register on http://api.developer.nokia.com/
//
nokia.Settings.set( "appId", "YOUR APP ID GOES HERE");
nokia.Settings.set( "authenticationToken", "YOUR AUTHENTICATION TOKEN GOES HERE");
/////////////////////////////////////////////////////////////////////////////////////
map = new nokia.maps.map.Display(document.getElementById('gmapcanvas'), {
'components': [
// Behavior collection
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.ZoomBar()
],
'zoomLevel': 5, // Zoom level for the map
'center': [41.0125,28.975833] // Center coordinates
});
// Remove zoom.MouseWheel behavior for better page scrolling experience
map.removeComponent(map.getComponentById("zoom.MouseWheel"));
var iconSVG =
'<svg width="33" height="33" xmlns="http://www.w3.org/2000/svg">' +
'<circle stroke="__ACCENTCOLOR__" fill="__MAINCOLOR__" cx="16" cy="16" r="16" />' +
'<text x="16" y="20" font-size="10pt" font-family="arial" font-weight="bold" text-anchor="middle" fill="__ACCENTCOLOR__" textContent="__TEXTCONTENT__">__TEXT__</text>' +
'</svg>',
svgParser = new nokia.maps.gfx.SvgParser(),
// Helper function that allows us to easily set the text and color of our SVG marker.
createIcon = function (text, mainColor, accentColor) {
var svg = iconSVG
.replace(/__TEXTCONTENT__/g, text)
.replace(/__TEXT__/g, text)
.replace(/__ACCENTCOLOR__/g, accentColor)
.replace(/__MAINCOLOR__/g, mainColor);
return new nokia.maps.gfx.GraphicsImage(svgParser.parseSvg(svg));
};
/* On mouse over we want to change the marker's color and text
* hence we create two svg icons which we flip on mouse over.
*/
var markerText = "1";
var colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#00FFFF", "#FF00FF" , "#000000"];
var markerIcon= createIcon("1", "#F00", "#FFF");
map.addListener("click", function (evt) {
var target = evt.target;
if (target instanceof nokia.maps.map.Marker && (target.clickCount === undefined) == false){
target.clickCount++;
var icon = createIcon(target.clickCount, colors[target.clickCount%7], "#FFF");
target.set("icon", icon);
map.update(-1, 0);
}
if (evt.target instanceof nokia.maps.map.Spatial) {
evt.stopImmediatePropagation();
}
});
var istanbul = new nokia.maps.map.Marker(
// Geo coordinate of Istanbul
[41.0125,28.975833],
{
icon: markerIcon,
clickCount : 1
}
);
/// Let's add another marker for comparison:
var bucharest = new nokia.maps.map.Marker(
// Geo coordinate of Bucharest
[44.4325, 26.103889],
{
icon: markerIcon,
clickCount: 1
}
);
// We add the marker to the map's object collection so it will be rendered onto the map.
map.objects.addAll([istanbul, bucharest]);
// ]]>
</script>
</body>
</html>

Loading/Refreshing 3d model in Google Earth

I'm using Google Earth in Web-development but I'm facing a weird situation, this is a simple code from the google code playground and it loads a 3D model into a google earth, if I refresh the page it wont load the model again,
http://savedbythegoog.appspot.com/?id=7f8638b214605a2327af223c613a6ae13874416b
Is there any way to fix it.
I'm facing with one more problem of loading the 3D models in Internet Explorer 8 in 32 bit XP machine, IE8 doesn't load the 3d model in google earth, you can check the link given. I'm also posting the js code below.
Please Help
<!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">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Earth API Sample</title>
<script src="http://www.google.com/jsapi?key=ABQIAAAAuPsJpk3MBtDpJ4G8cqBnjRRaGTYH6UMl8mADNa0YKuWNNa8VNxQCzVBXTx2DYyXGsTOxpWhvIG7Djw" type="text/javascript"></script>
<script type="text/javascript">
function addSampleButton(caption, clickHandler) {
var btn = document.createElement('input');
btn.type = 'button';
btn.value = caption;
if (btn.attachEvent)
btn.attachEvent('onclick', clickHandler);
else
btn.addEventListener('click', clickHandler, false);
// add the button to the Sample UI
document.getElementById('sample-ui').appendChild(btn);
}
function addSampleUIHtml(html) {
document.getElementById('sample-ui').innerHTML += html;
}
</script>
<script type="text/javascript">
var ge;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCallback, failureCallback);
// addSampleButton('Create a 3D Model!', buttonClick);
}
function initCallback(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
// add some layers
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
la.setRange(100000);
ge.getView().setAbstractView(la);
create3dModel();
document.getElementById('installed-plugin-version').innerHTML =
ge.getPluginVersion().toString();
}
function failureCallback(errorCode) {
}
function create3dModel() {
// Create a 3D model, initialize it from a Collada file, and place it
// in the world.
var placemark = ge.createPlacemark('');
placemark.setName('model');
var model = ge.createModel('');
ge.getFeatures().appendChild(placemark);
var loc = ge.createLocation('');
model.setLocation(loc);
var link = ge.createLink('');
// A textured model created in Sketchup and exported as Collada.
link.setHref('http://earth-api-samples.googlecode.com/svn/trunk/examples/' +
'static/splotchy_box.dae');
model.setLink(link);
var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
loc.setLatitude(la.getLatitude());
loc.setLongitude(la.getLongitude());
placemark.setGeometry(model);
la.setRange(300);
la.setTilt(45);
ge.getView().setAbstractView(la);
}
function buttonClick() {
create3dModel();
}
</script>
</head>
<body onload="init()" style="font-family: arial, sans-serif; font-size: 13px; border: 0;">
<div id="sample-ui"></div>
<div id="map3d" style="width: 500px; height: 380px;"></div>
<br>
<div>Installed Plugin Version: <span id="installed-plugin-version" style="font-weight: bold;">Loading...</span></div>
</body>
</html>
If that links doesn't work copy the code and paste it in a text file and rename it to .html and then execute it.
Even I had faced the same problem with collada models and internet explorer, the code u have given is working fine in rest of the browsers like chrome and mozilla.
check out this link, but in this case they are loading a kml file and not directly loading collada models into the browser using javascript.

jQuery element.remove undo

I have code(thanks to roosteronacid) which removes web page elements when user click on them. I need to add additional functionality to undo action - revert removed elements. Any idea how to do element.remove undo with jQuery?
Regards,
Tomas
You can store a reference to removed elements by assigning the return value of remove() to a variable:
// Remove the element and save it in a variable
var removed = $('#myElement').remove();
Later, providing the variable is in scope, we can add the element back using various DOM insertion methods:
// Insert the removed element back into the body
removed.insertAfter('#anotherElement');
Looking at the code provided by roosteronacid, it doesn't save the reference so you would have to modify that code accordingly.
There is another method for this: .detach: http://api.jquery.com/detach/ that removes an element without destroying it.
You still have to "save" the element though (look at the example provided in the docs.)
You could take the approach many apps take for undo and save the complete body state before each remove, I've reworked #roosteronacid's code thus:
index.htm
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="index_files/jquery-1.js" type="text/javascript"></script>
<script src="index_files/index.js" type="text/javascript"></script>
<title>index</title>
<script type="text/javascript">var stack = Array();</script>
</head><body>
<h1>Test</h1>
<p>Test</p>
<div>Test</div>
Test
<span>Test</span>
Undo
</body></html>
index.js
$(function ()
{
initialise();
});
function initialise() {
$("* :not(body,a)").mouseenter(function ()
{
var that = $(this);
var offset = that.offset();
var div = $("<a />",
{
"title": "Click to remove this element",
css: {
"position": "absolute",
"background-color": "#898989",
"border": "solid 2px #000000",
"cursor": "crosshair",
width: that.width() + 6,
height: that.height() + 2
},
offset: {
top: offset.top - 4,
left: offset.left - 4
},
click: function ()
{
div.remove();
var state = $("body *");
stack.push(state);
that.remove();
},
mouseleave: function ()
{
div.fadeTo(200, 0, function ()
{
div.remove();
});
}
});
that.after(div.fadeTo(200, 0.5));
});
};
Well instead of removing them, you can do jQuery("#someElement").hide(); and then after if you want to get them back jQuery("#someElememt").show(); would be nice solution. Since its alters it display property.

JavaScript only works when page is reloaded

I have a fairly simple page that displays an image in a pop-up window. The onLoad event simply takes the querystring, populates an image tag with that value, then resizes the image and window to match.
For some reason, this only works for me when the page is reloaded/refreshed. Or, once the image has been displayed once, it will work from then on, even though caching is turned off. But any time an image is viewed the first time, the page comes up blank with no errors thrown.
Any suggestions?
Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Zoom</title>
<meta http-equiv="Pragma" content="no-cache" />
<script type="text/javascript">
function getImage() {
//get the query string (everything after the ?)
var filename = window.location.search.substring(1);
//find the image control
var imageWorking = document.getElementById('dynamicImage');
//assign the image source
imageWorking.src = '../Images/' + filename;
//create an image variable
var newImg = new Image();
//assign the source to match the page image
newImg.src = imageWorking.src;
//get the width and height
var width = newImg.width;
var height = newImg.height;
//set the page image width and height to match the disk image
imageWorking.width = width;
imageWorking.height = height;
//set the window to be just larger than the image
window.resizeTo(width + 50,height + 50);
}
</script>
</head>
<body onload="getImage();">
<img src="images/spacer.gif" id="dynamicImage" alt="Image Zoom" width="1" height="1" />
</body>
</html>
The page is called using the following function:
function imageZoom(imageName)
{
window.open('ImageZoom.htm?' + imageName + '','imageZoom','width=400,height=400,menubar=no,toobar=no,scrollbars=yes,resizable=yes');
}
Write the IMG tag dynamically using JavaScript during page load, and resize the window at onload:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Zoom</title>
<meta http-equiv="Pragma" content="no-cache" />
<script type="text/javascript">
function sizeWindow() {
//find the image control
var img = document.getElementById('dynamicImage');
//set the window to be just larger than the image
window.resizeTo(img.width + 50, img.height + 50);
}
</script>
</head>
<body onload="sizeWindow();">
<script type="text/javascript">
var filename = window.location.search.substring(1);
document.write("<img src='../Images/" + filename + "' id='dynamicImage' alt='Image Zoom' />");
</script>
</body>
</html>
You need to set the SRC of the <img> to something initially. If you don't desire to display anything, just use a 1x1 pixel transparent GIF.
have you tried bind the getImage function to the window's onload event rather then to the body's onload?

Categories

Resources