Preface: I have contacted google and read the documentation. When this is finished it will display the map on the next page and have autosuggest on the first - I will not be violating the terms and conditions this way, so please dont start a flame war
I have set about trying to create my own minimal geocoder which geocodes without showing a map on the current page. I have found that there is no example code online for doing this! I am new to jquery but this is the best I could come up with. However, low and behold it doesn't work.
I am sure I have done something stupid, so I would appreciate it if someone could let me know if they spot any obvious reasons why this wouldn't work. I have never made a javascript before.
JSFiddle Link: http://jsfiddle.net/njDvn/9/
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function getLatLng() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
<input id="lat" type="textbox" value="lat">
<input id="lng" type="textbox" value="lng">
</div>
</body>
</html>
well first 2 things I can see are that the onclick of the button is calling codeAddress(), but you have not declared that function - you can change that to getLatLng() and it should work then. Plus the <body onload is calling initialize() which is also not declared. While that should not prevent the geocoder from firing you should probably fix it.
Related
I am trying to set up a price calculation tool in JS. This is going to calculate amount of kilometers between a set address (business address) and the customer's address, which they can enter into an <input> field.
The script will then round off the amount of kilometers to whole euros (no decimals), and display this as the price (charge of this service is 1 euro per kilometer, so no other calculation required to get the price).
So far I came up with the below code. When I enter this into a .html document in notepad, and open that file with Firefox, it works. However, this needs to be implemented on a Wordpress website.
I put the JS code in the <head> and the rest in the <body> (as shown below). But for some reason it won't work in Wordpress. (on the Wordpress site, as well as the notepad file, I put the script between <script> tags of course)
I tried reading the Wordpress documentation about using JS, and as far as I can see, pasting the code directly into the header is a valid way of making it work (especially for testing purposes) and everything should work, but evidently doesn't. I have also used Google, as well as the Stackoverflow search to try and find an answer, but was obviously unsuccessful.
All help would be greatly appreciated!
The website on which it should be, but isn't, working is: http://www.aircostadskanaal.nl/haal-en-breng-service/
The <head>:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var melbourne = new google.maps.LatLng(-37.813187, 144.96298);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: melbourne
}
}
function calcRoute() {
var start = "Ceresstraat 11, Stadskanaal, Netherlands";
var end = document.getElementById("end").value;
var distanceInput = document.getElementById("distance");
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceInput.value = Math.round(response.routes[0].legs[0].distance.value / 1000);
}
});
}
The <body>:
<body onload="initialize()">
<div>
<p>
<!--<label for="start">Start: </label>
//<input type="text" name="start" id="start" />-->
<label for="end">Adres: </label>
<input type="text" name="end" id="end" />
<input type="submit" value="OK" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Prijs (€): </label>
<input type="text" name="distance" id="distance" readonly="true" />
</p>
</div>
edit; removed line to set map as I decided not to include the map on the website. This has not fixed the problem unfortunately.
The line map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); in function initialize is referencing element with id="map_canvas" but I can't see it in the markup. Did you by any chance forget it?
Found the answer myself. Thanks everyone for your input
The issue was directionsDisplay = new google.maps.DirectionsRenderer(); which was defined as a variable in function initialize(), but also used in function calcRoute().
I defined it as a global variable, and now the script works.
I'm just starting to learn JavaScript and therefore do not know much about how Forms are used or how to read from them. I'm trying to play around with Google's Geocode, and need some help with building a JS Form to read from.
I have the following JS code, outputting the longitude & latitude, and simply need a form to store some addresses in. The code I have looks as follows:
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( {'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
results[0].geometry.location.latitude
results[0].geometry.location.longitude
}
else
{
alert("Geocode was not successful for the following reason: " + status)
}
});
I'd like some help if possible to build a form this code can read an address from, where the ElementID = "address". How would such a form look? I'd much appreciate if someone could take a minute or two and explain how the JS works with the form. Any help is appreciated! Thank you, guys.
JS dosent care what the element is you just need to get the reference of the form from the DOM then you can do what you want (get the value).
a simple form can look like this
<form>
First name:<br>
<input type="text" id="firstname"><br>
Address:<br>
<input type="text" id="address">
</form>
<button onclick="myFunc()">Done!</button>
So when the button is click it will run a function myFunc which will get your data from the form and alert it.
function myFunc(){
var name = document.getElementById("firstname").value;
var address = document.getElementById("address").value;
alert(name + " lives at " + address);
}
more on getting elements by id here
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
you can also use jquery
function myFunc(){
var name = $("#firstname").val();
var address = $("#address").val();
alert(name + " lives at " + address);
}
https://api.jquery.com/id-selector/
First create a Form in html. Include your external javascript file in it.
<head>
<script type="text/javascript" src="index.js"></script> //index.js is name of javascript file which is in same location of this jsp page.
</head>
<body>
<form name="EmployeeDetails" action="ServletEmployee" method="post">
Employee Name:<input type="text" id="name"><br>
EmployeeID:<input type="text" id="employID"><br>
<input type="submit" value="Submit">
</form>
<input type="button" name="Click" id="mybutton" onclick="myButtonClick">
</body>
In your external javascript file...that is index.js
window.onload = function(){ // function which reads the value from html form on load without any button click.
var employeename = document.getElementById("name").value;
var employeeid = document.getElementById("employID").value;
alert("Name : "+employeename+" : EmployeeID : "+employeeid);
}
function myButtonClick(){ // function to read value from html form on click of button.
var empname = document.getElementById("name").value;
var empid = document.getElementById("employID").value;
alert("Name : "+empname+" : EmployeeID : "+empid);
}
I have a html file on my website domain (devodeliver.co.uk) which calls on my API Key with the code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY-KEY"></script>
In the Developers Console I have tried adding every combination of my domain URL as you can see below
But when I load my site it shows the map for a millisecond then returns with the error "Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error_.bb # MY-KEY:32" - basically saying I haven't given my website permission to access that API Key. But even if I don't set any referrers, it come back with the same error message. I've also waited way over 5 minutes for the API to take affect. Please, what am I doing wrong?! I've spent almost 16 hours trying to figure this out & I can't seem to for the life of me. HELPPPP!
Full HTML code:
<html>
<head>
<style type="text/css">
#map
{
height:400px;
width:400px;
display:block;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7-LTLEupUWBJBWl1GpOWPwkMvxzf8itQ"></script>
<script type="text/javascript">
function getPosition(callback) {
var geocoder = new google.maps.Geocoder();
var postcode = document.getElementById("postcode").value;
geocoder.geocode({'address': postcode}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
callback({
latt: results[0].geometry.location.lat(),
long: results[0].geometry.location.lng()
});
}
});
}
function setup_map(latitude, longitude) {
var _position = { lat: latitude, lng: longitude};
var mapOptions = {
zoom: 16,
center: _position
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: mapOptions.center,
map: map
});
}
window.onload = function() {
setup_map(51.5073509, -0.12775829999998223);
document.getElementById("form").onsubmit = function() {
getPosition(function(position){
var text = document.getElementById("text")
text.innerHTML = "Marker position: { Longitude: "+position.long+ ", Latitude:"+position.latt+" }";
setup_map(position.latt, position.long);
});
}
}
</script>
</head>
<body>
<form action="javascript:void(0)" id="form">
<input type="text" id="postcode" placeholder="Enter a postcode">
<input type="submit" value="Show me"/>
</form>
<div id="map"></div>
<div id="text"></div>
</body>
</html>
Here, when I tested it, it gives me the error "Google Maps API error: ApiNotActivatedMapError" on the JS console.
Take a look for this issue on: https://developers.google.com/maps/documentation/javascript/error-messages#deverrorcodes
When you use a library or service via the Maps-Javascript-API, and use a key, you need to activate the Google Maps JavaScript API .
Make sure to activate the Google Maps JavaScript API for your project.
Also,
take a look on this other topic about Enable the Google Maps Jvascript API: Google Map error: InvalidKeyOrUnauthorizedURLMapError
Im trying to get my current location but the problem is the address which the marker points is only the nearest street where I am now. How can I get my place accurately?
Heres the screen shot. Thanks in advance :)
Click here
<input type="button" value="Show Location" onclick="showlocation()"/>
<br/>
Latitude: <span id="latitude">..</span> <br>
Longitude: <span id="longitude">..</span><br>
Address: <span id="add">..</span><br>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function showlocation(){
navigator.geolocation.watchPosition(callback);
}
function callback(position){
document.getElementById('latitude').innerHTML=position.coords.latitude;
document.getElementById('longitude').innerHTML=position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var latLng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({
latLng: latLng
},
function(responses)
{
if (responses && responses.length > 0)
{
address(responses[0].formatted_address);
}
else
{
alert('Not getting Any address for given latitude and longitude.');
}
}
);
}
function address(str)
{
document.getElementById('add').innerHTML = str;
}
</script>
Use Geolocation API. To obtain your current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information.
When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.
This documentation and example might help you.
On one of my pages in Drupal, I have a panel that contains the following html code:
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
var dirService, initAddr, endLoc, doc;
function initialize() {
dirService = new google.maps.DirectionsService();
initAddr = "85 E San Fernando Street San Jose, CA 95113";
}
function showLocation() {
doc = document.getElementById("results_area");
endLoc = document.forms[0].address2.value;
findFromAddress();
}
function findFromAddress() {
dirService.route({'destination': initAddr, 'origin': endLoc, 'travelMode': google.maps.TravelMode.DRIVING}, function (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
var distance = result.routes[0].legs[0].distance.value;
var miles = Math.round(distance * 0.000621371192 * 100) / 100;
alert("Distance from Loves Cupcakes is roughly" + miles
+ " miles" + "Estimated price is (price)" );
}
else {
alert("INVALID ZIP CODE");
}
});
}
</script>
</head>
<body onload="initialize()">
<p> Enter in zip code of desired delivery location</p>
<form action="#" onsubmit="showLocation(); return false;">
<p><input class="address_input" name="address2" size="20" type="text" /> <input name="find" type="submit" value="Search" /></p>
</form>
<p id="results_area"> </p>
Simply put, it takes a zipcode and calculates the distance from a specified location.
The HTML page works on its own, but when I enter it into a panel, some weird stuff happens that I don't understand. When I hit the "Submit" button, the page is reloaded, but with a slightly different URL and no alert box pops up. The URL changes from ../contact_us to ../Contact_Us?address2=&find=Search#. I understand the address2 and search are elements from my HTML code, but can anyone help me figure out why this is happening (I am assuming it has something to do with drupal, not the code itself, but not too sure)?
When the submit button is clicked, the browser sends a HTTP GET request to the address with the address2 and find values as parameters.
In your case, address2 has no value and find has a value of 'Search'
See here for a comprehensive explanation : https://www.rfc-editor.org/rfc/rfc3986#section-3