I want to change Images of my markers in this javascript
can anybody help me out from this?
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg&sensor=true_or_false"
type="text/javascript"></script>
<script type="text/javascript">
function geocoder(){
var place = document.getElementById("textarea").value;
geocoder = new GClientGeocoder();
geocoder.getLatLng(place, function(point)
{
if (!point)
{
alert(place + " not found");
}
else
{
var info = "<h3>"+place+"</h3>Latitude: "+point.y+" Longitude:"+point.x;
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(point, 13);
map.setUIToDefault();
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(point.toUrlValue(5));
}
}
);
}
</script>
</head>
<body>
<table width="347" border="1" align="right">
<tr>
<td width="168"> </td>
<td width="163"> </td>
</tr>
<tr>
<td height="45"><div align="right">Address : </div></td>
<td><form id="form1" name="form1" method="post" action="">
<label>
<textarea name="textarea" id="textarea"></textarea>
</label>
</form>
</td>
</tr>
<tr>
<td><form id="form2" name="form2" method="post" action="">
<label>
<input name="Button" type="Button" id="Button" value="Submit" onClick="geocoder()" onunload="GUnload()"/>
</label>
</form>
</td>
<td> </td>
</tr>
</table>
<div id="map_canvas" style="width: 500px; height: 300px"></div>
</body>
</html>
The GMarker constructor takes a GMarkerOptions as the second parameter. You can use that to specify a GIcon to use for the marker.
It may look something like this:
var marker = new GMarker(point, {
icon: new GIcon(
G_DEFAULT_ICON,
'/images/custom_marker.png')
});
This uses the default icon as a baseline, and changes just the main image. There are a number of other properties you can set on the icon, depending on whether you need to change the shadow, etc.
You can also upload your image to a site, like the Google Map Custom Marker Maker, which will create the extra images and javascript for the icon.
Finally, check out the Custom Icons for Markers topic on the Google Maps group.
You can specify your marker parameters like so:
var num = 1 //etc..
var icon = new GIcon();
icon.image = "/mapIcons/icon"+num+".png";
icon.iconSize = new GSize(20,32);
icon.shadowSize = new GSize(20, 34);
icon.iconAnchor = new GPoint(11, 15);
icon.infoWindowAnchor = new GPoint(11, 15);
icon.shadow = "";
Related
Function: Enter a phone number (ex: 555-555-5555) into a text field. The text field prints the number out flat (hidden by CSS). Then Javascript picks up that number by ID and splits it apart by the hyphens and injects the array split up into a FoneFinder URL search string to display the results from that site in a pop-up window.
Problem: The pop-up is working fine, however when I click on the link to spawn the link it opens in the main page as well as the pop-up. The main page should not change.
The pop-up code works fine on other pages and doesnt overwrite the main page. It has to be how the javascript is injecting the html link into the page that is messing it up, but I cant figure out why.
Any help or insights would be appreciated.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style>
#target_num_result {
display: none;
}
#target_num_search {
font-size: small;
}
</style>
<!-- NewWindow POP UP CODE -->
<script LANGUAGE="JavaScript">
function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}
</script>
<!-- Script to read the target phone number and split it by hyphens and show a Search link to Fonefinder.net -->
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('#target_num').on('keyup', function() {
var my_value = $(this).val();
$('#target_num_result').html(my_value);
var arr = my_value.split('-');
$("#target_num_search").html(" <a href=http://www.fonefinder.net/findome.php?npa=" + arr[0] + "&nxx=" + arr[1] + "&thoublock=" + arr[2] + "&usaquerytype=Search+by+Number&cityname= title=FoneFinder onclick=NewWindow(this.href,'FoneFinderLookup','740','680','yes');>!BETA!FoneFinder Search!BETA!</a>");
});
});//]]>
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<table cellpadding="2" cellspacing="0" style="width: 100%">
<tr>
<td style="width: 180px">Phone #:</td>
<td><label> <input class="text" type="text" name="target_num" id="target_num" /></label><span id="target_num_result"></span><span id="target_num_search"></span></td>
</tr>
</table>
<label>
<input class="button" type="submit" name="submit" id="submit" value="Create" />
</label>
</form>
</body>
</html>
what you need to add is the following:
$('#target_num_search').on('click', 'a', function (event) {
event.preventDefault();
var url = $(this).attr('href');
NewWindow(url,'FoneFinderLookup','740','680','yes');
})
This way you can remove the onclick attribute and move the function call to js. See the working jsfiddle
you should return false for prevents default action to go link 'href' when onlick event.
(please notes , - comma operator to whatever Function returns... It's just hack. don't use.)
BTW,
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style>
#target_num_result {
display: none;
}
#target_num_search {
font-size: small;
}
</style>
<!-- NewWindow POP UP CODE -->
<script LANGUAGE="JavaScript">
function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}
</script>
<!-- Script to read the target phone number and split it by hyphens and show a Search link to Fonefinder.net -->
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('#target_num').on('keyup', function() {
var my_value = $(this).val();
$('#target_num_result').html(my_value);
var arr = my_value.split('-');
var html_tpl = " <a href=http://www.fonefinder.net/findome.php?npa=" + arr[0] + "&nxx=" + arr[1] + "&thoublock=" + arr[2] + "&usaquerytype=Search+by+Number&cityname= title=FoneFinder onclick=\"return NewWindow(this.href,'FoneFinderLookup','740','680','yes'), false\" target='_blank'>!BETA!FoneFinder Search!BETA!</a>";
$("#target_num_search").html(html_tpl);
});
});//]]>
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<table cellpadding="2" cellspacing="0" style="width: 100%">
<tr>
<td style="width: 180px">Phone #:</td>
<td><label> <input class="text" type="text" name="target_num" id="target_num" /></label><span id="target_num_result"></span><span id="target_num_search"></span></td>
</tr>
</table>
<label>
<input class="button" type="submit" name="submit" id="submit" value="Create" />
</label>
</form>
</body>
</html>
I am having a problem deleting user added markers upon a new marker being add. I originally tried to go about the right click method but I only want the user to be able to create one marker at a time. Can someone please help me?
function addMarker(location){
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
var form = $("#form").clone().show();
var contentString = form[0];
infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(GlobalMap,this);
});
infowindow.open(GlobalMap,marker);
markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "dragend", function (mEvent){
populateInputs(mEvent.latLng);
});
google.maps.event.addListener(marker, 'rightclick', function(){
marker.setMap(null)
});
}
google.maps.event.addDomListener(window, 'load', window.onload);
function populateInputs(pos){
document.getElementById("latitude").value=pos.lat()
document.getElementById("longitude").value=pos.lng();
}
function clearOverlays(){
for(var i = 0; i <markers.length; i++){
markers[i].setMap(null);
}
}
var markers= [];
var center= null;
var GlobalMap = null;
var marker = null;
var infowindow;
var geocoder = new google.maps.Geocoder();
window.onload = function() {
// Creating a reference to the mapDiv, which is defined in the host html file
var mapDiv = document.getElementById('map');
// Creating a latLng for the center of the map, these coordinates set the center of the initial map to the center of Springfield.
var latlng = new google.maps.LatLng(37.1950, -93.2861);
// Creating an object literal containing the properties
// we want to pass to the map
var options = {
center: latlng,
zoom: 11, // This zoom level shows the OTO area.
mapTypeId: google.maps.MapTypeId.ROADMAP // We want to show the data on the road map, as opposed to the satellite view.
};
// Now Creating the map
GlobalMap = new google.maps.Map(mapDiv, options);
oto.setMap(GlobalMap);
$('#address').keypress(function(e){
if(e.which==13){
e.preventDefault();
window.geocode();
}
});
markers.push(marker);
google.maps.event.addListener(GlobalMap, "click", function (event)
{
addMarker(event.latLng);
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLong = marker.latLng;
$latitude.value = latLong.lat();
$longitude.value = latLong.lng();
});
}
Here is the HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Public Comment</title>
<link type="text/css" href="css/style.css" rel="stylesheet" media="all" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var otoTableId = '1gPq1ryMpY1S_ovp6pIl0LvqDJkGNUUGShPpDCxtj';
var GlobalMap = null;
//var Urbanlayer = new google.maps.KmlLayer('http://www.ozarkstransportation.org/GIS/OTOBoundary.kml',{preserveViewport:true, suppressInfoWindows:true});
</script>
<script type="text/javascript" src="js/map.js"></script>
</head>
<body>
<!-- Top Banner Bar !-->
<button onclick="toggle_visibility('checkboxes')" style="float: right;">Toggle legend</button>
<div id="banner"><img src="http://www.ozarkstransportation.org/GIS/OTOgraphicSmall.jpg" border="none" height= "66">
<input type="text" id="address" class="form-control" placeholder="e.g., 205 Park Central East, Springfield MO" size="35">
<span class="input-group-btn">
<button onClick="window.geocode()" class="btn btn-success" value=>
<span class="glyphicon glyphicon-map-marker"></span>Go
</button>
</span>
<em id = "banner_text" align="absmiddle">Left click to drop a marker.<br> Right click to delete most recent marker.<br>Cancel to reset with no markers.</em>
</div>
<!-- The Google Map Window !-->
<div id="map"></div>
<!-- The Layer Toggle Window !-->
<div id="checkboxes">
<h3>Left click to drop a marker.<br> Right click to delete marker.<br>Cancel to reset with no markers.</h3>
<br><input type="checkbox" id="NAME" checked="true" onClick="toggleOto()"/><i class="fa fa-minus"></i>OTO Boundary<br />
<table bgcolor="#FFFFFF"><tr><td>
<br>
<!-- <center><b><font color="#000000">Use "add a marker" tool to leave comment.<br> Drag marker to desired location.</font></b></center> !-->
<br>
<center><font size="-1">
OTO MPO |
<!-- #BeginDate format:Am1 -->August 20, 2015<!-- #EndDate --> |
<a target="_blank" href="http://www.ozarkstransportation.org/GIS/Disclaimer.pdf">Disclaimer</a>
</font><br>
<font size="-2">For best results view in Google Chrome</font><br></center>
</td></tr></table>
</div>
<!-- The Bottom Messaging !-->
<div id="container">
</div>
<div id="entryform">
<form role="form" id = "form">
<iframe id ="myFrame" src="https://docs.google.com/forms/d/1EjeuI7ddocJIUr8RALi_WZIuqgQlfgVG9WMqvKR0lSw/viewform?embedded=true" width="500" height="500" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<h4>Please copy and paste the Latitude and Longitude values into the above form.</h4>
<div class="form-group">
<label><b>Latitude</b></label>
<input id ="latitude" type="text" class="form-control" name="lat" `enter code here`placeholder="Latitude" required="yes">
</div><br>
<div class="form-group">
<label><b>Longitude</b></label>
<input id ="longitude" type="text" class="form-control" name="lng" placeholder="Longitude" required="yes">
</div><br>
<div class="form-group">
<!-- <button class="btn btn-primary" id="submit-button">Submit</button> !-->
<button class="btn btn-primary" id ="delete-button">Cancel</button>
</div>
</form>
</div>
</body>
</html>
Looks like your marker is already global. This should work:
function addMarker(location){
// check if the marker already exists and has a .setMap method
if (marker && marker.setMap) {
// remove existing marker from the map
marker.setMap(null);
}
// create the marker
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
// ... rest of your code
I have a problem using responsive Google map on my page. I am using Google Map API v3 & bootstrap 3 CSS to make my site mobile first & responsive. I intend to get users address either by using Google places API by automatically filling up the address form or by getting coordinates from the map and GPS.
I am using radio button to enable user to select either of the two options. The address form is selected as default option. When Use Map option is selected, the form has to be hidden & the Google map should be visible in its place but that just won't happen. I used Mozilla's Inspect Element option to check if the map is loaded in the background & yes it did.
The problem:
The map just wont show up on the specified div which is div id="map-canvas" Except that everything works fine, I even managed to get static Google map as image to be displayed in the same div appending the image file to the div using .innerHTML() function.
The solution I need ia to be able to display the map inside the map-canvas div & the map should be responsive.
Here's my code (html + js + css) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Address form</title>
<!-- Bootstrap Core CSS -->
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<!--Start of CSS for Google Places API-->
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<style>
#locationField{
position: relative;
}
</style>
<!--End of assets for G Places API-->
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body onload="initialize()">
<div class="container">
<div>
<legend>Address</legend>
</div>
<form class="form-horizontal" action="" method="POST">
<fieldset>
<div class="well col-md-12">
<h4><strong>Where are you?</strong></h4><br /><br />
<legend></legend>
<div class="col-md-6">
<h4><strong>Your Information</strong></h4>
<legend></legend>
<div class="control-group">
<label class="control-label" for="location">Provide your location:</label>
<div class="controls">
<label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="form" class="input-xlarge" checked required>Use Form </label>
<label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="map" class="input-xlarge" onClick="getLocation()" required>Use Map </label>
<br />
</div>
</div>
<div class="address-form">
<div class="control-group">
<label class="control-label" for="address">Address</label>
<div class="controls">
<div id="locationField">
<input type="text" id="autocomplete" name="address" placeholder="Enter your address" class="form-control" required>
</div>
</div>
</div>
<br />
<div class="control-group">
<table class="table table-bordered table-hover">
<tr>
<td><label class="control-label">Locality</label></td>
<td><input class="form-control" id="street_number" name="tole" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Street</label></td>
<td><input class="form-control" name="street" id="route" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">City</label></td>
<td><input class="form-control" id="locality" name="city_vdc" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Region</label></td>
<td><input class="form-control" name="region" id="administrative_area_level_1" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Zip code</label></td>
<td><input class="form-control" id="postal_code" name="zip" disabled=""></input></td>
</tr>
<tr>
<td><label class="control-label">Country</label></td>
<td><input class="form-control" name="country" id="country" disabled="true"></input></td>
</tr>
</table>
</div>
</div>
<div class="map-canvas control-group">
<div id="map-canvas">
<!--Map Should Be Here-->
</div>
</div>
</div>
<!-- Button -->
<div class="control-group col-md-12">
<br /><legend></legend>
<div class="controls">
<button type="submit" name="submit" class="btn btn-success pull-right">Submit</button>
<br /><br />
</div>
</div>
</div>
</fieldset>
</form>
</div>
<!--JS for Address Mode Selection-->
<script type="text/javascript">
$("input:radio[name=loc_method]:first-child").click(function(){
if($(this).val()=="form"){
$(".address-form").css("display","block");
$(".map-canvas").css("display","none")
}else{
$(".map-canvas").css("display","block");
$(".address-form").css("display","none");
}
})
</script>
<!--JS API For Google Places Address Form Autofill-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script type="text/javascript">
var y = document.getElementById("map-canvas");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError,{
enableHighAccuracy: true,
timeout:30000
});
} else {
y.innerHTML = "Geolocation is not supported by this browser, choose <b>Use Form</b> option to fill the address form.";
}
}
function showPosition(position) {
//These commented codes below are to display static GMap of the acquired coordinates as image in the div id="map-canvas" which I did successfully
/*var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=320x240&sensor=true";
y.innerHTML = "<br />Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude +
"<br>Altitude: " + position.coords.altitude +
"<br>Position Accuracy: " + position.coords.accuracy +
"<br>AltitudeAccuracy: " + position.coords.altitudeAccuracy +
"<br><img src='"+img_url+"'>";*/
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
//google.maps.event.addDomListener(window, 'load', initialize);
var point = new google.maps.LatLng(position.coords.atitude, position.coords.longitude);
var marker = new google.maps.Marker({
position:point,
map:map,
title:'Rescue Team Needed Here # <br />' + position.coords.latitude + 'deg. South & <br />' + position.coords.longitude + 'deg. East',
draggable:true,
});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation. If you are concerned with your privacy choose <b>Use Form</b> option to fill the address form."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable. Choose <b>Use Form</b> option to fill the address form."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out. Choose <b>Use Form</b> option to fill the address form."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred. Choose <b>Use Form</b> option to fill the address form."
break;
}
}
</script>
<script>
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'],
componentRestrictions: {country: 'np'}});
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
Hope this you looking for.. which i understand from your question.
Define width:100%
#map-canvas {
margin: 20px 0;
padding: 0;
height: 300px;
float: left;
width: 100%;
}
HTML CODE
<div class="col-md-12">
<div id="map-canvas" style="position: relative; overflow: hidden; transform: translateZ(0px); background-color: rgb(229, 227, 223);"></div>
</div>
Adding class col-xs-12 to your map div will do the job.
Go ahead re-size the windows, the map will automatically resize, remaining in its div.
.yourdiv {
border: solid;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div class="yourdiv col-xs-12" id="map-canvas"></div>
</body>
</html>
This is my html code,During this simple code dynamically by pressing + button I can increase number of inputs. Now I want to store allRows.length+1 value into myHiddenField after adding a new input and finally I can see the total number of my inouts html input value, same as below :
<input type="hidden" name="myHiddenField" value="**I want to store allRows.length+1 value here **" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);//appends the cloned row as a new row
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<input type="hidden" name="myHiddenField" value="**I want to store allRows.length+1 value here **" />
<tr>
<td width="191"><input type="text" name="textfield_A" /></td>
<td width="191"><input type="text" name="textfield_B" /></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>
How can I solve this issue and store javascript value into an input value through my html form?
Add an id="myHiddenField" attribute in your hidden input and in Javascript, you can just
document.getElementById("myHiddenField").value = allRows.length+1;
You obviously don't need jQuery to assign a value on an input.
Check my jsfiddle. Add input type hidden in your html and in Javascript give like below
DEMO HERE
document.getElementById("myHiddenField").value = allRows.length;
At the end of the addRow add:
function addRow(r){
// ...
// ...
// ...
var hiddenInput = document.querySelector("input[name='myHiddenField']");
hiddenInput.value = document.querySelectorAll("td input[type='text']").length + 1;
}
TRy this
<input type="hidden" name="myHiddenField" value="**I want to store allRows.length+1 value here **" id="numberOfRows" />
And your script should be like this
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);//appends the cloned row as a new row
$('#numberOfRows').val($('table tr').length+1);
}
Change your code to following
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var currval = document.getElementById('myHiddenField').value;
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);//appends the cloned row as a new row
document.getElementById('myHiddenField').value = ++currval;
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<input type="hiddden" name="myHiddenField" id="myHiddenField" value="1" />
<tr>
<td width="191"><input type="text" name="textfield_A" /></td>
<td width="191"><input type="text" name="textfield_B" /></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>
I deliberately left hidden type to view so the changes can be viewed, you can later corect it.
See you can use attribute selector of jquery:
var $hiddenInput = $('input[name="myHiddenField"]'),
$rowLenth = $hiddenInput.closest('table tr').length+1;
$hiddenInput.val($rowLenth);
I'm doing some geocoding using the google maps API.
The user fill a form with some address, and when the submit button is clicked, a codeAddress() function is called, which is supposed to perform the geocoding, but it does not work.
As a test, I hardcoded the address and call the codeAddress function when the document in an initialize().
When codeAddress is called when the page is ready, it works ok, but when it's called by the onclick script, it doesn't work (no errors returned by firebug!).
Anybody can help?
Thanks
(you can paste the code in here: http://code.google.com/apis/ajax/playground/?exp=maps#map_simple, or change the google api key)
<!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" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps API Sample</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q"></script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
codeAddress();
}
}
function codeAddress() {
var geocoder = new GClientGeocoder();
var address = "paseo montjuic, 30, barcelona, spain";
geocoder.getLatLng( address, function(point) {
if (point) {
alert(point);
} else {
alert("Geocode was not successful");
}
});
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()" style="font-family: Arial;border: 0 none;">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<form action="" method="POST">
<!-- stuff -->
<input type="Submit" value="Submit" onclick="codeAddress();" />
</form>
</body>
</html>
Looks to me right after codeAddress(); is called on the onclick event, your POST is done immediately. Thus it looks to you that the code failed, but in fact it is working.
What you can do is:
1) Remove the form, just a button using the onclick event. Example:
<input type="button" value="Submit" onclick="codeAddress();" />
2) Disable submitting form when event onclick hits by adding return false;. Example:
<form action="" method="POST">
<!-- stuff -->
<input type="Submit" value="Submit" onclick="codeAddress();return false;" />
</form>