Uncaught ReferenceError: SearchAddress is not defined at HTMLInputElement.onclick - javascript

I am trying to make a google map API that has moveable points but also includes a search option to search address. I have gotten the draggable points but get a Uncaught ReferenceError: SearchAddress is not defined at HTMLInputElement.onclick when I try and run this code. I cannot figure out how to get this to work. I have tried removing the SearchAddress function out of the other InitMap function but still Help would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<link rel="stylesheet" type="text/css" href="stylesheet1.css">
<script type="text/javascript">
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var moveloc1 = {lat: 55, lng: -7.3};
var moveloc2 = {lat: 55, lng: -7.1};
function initMap()
{
console.log("error checker1");
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: {lat: 55, lng: -7.3} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer
({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function()
{
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(moveloc1, moveloc2 , directionsService,
directionsDisplay);
console.log("error checker2");
function SearchAddress()
{
console.log("error checker3");
var locate1 = document.getElementById("pass1").value;
var locate2 = document.getElementById("pass2").value;
console.log(locate1);
console.log(locate2);
geocoder.geocode( { 'pass1': address}, function(results, status)
{
if (status == 'OK')
{
map.setCenter(results[0].geometry.location);
moveloc1 =
({
position: results[0].geometry.location
});
}
else
{
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
}
function displayRoute(origin, destination, service, display)
{
service.route
({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
},
function(response, status)
{
if (status === 'OK')
{
display.setDirections(response);
}
else
{
alert('Could not display directions due to: ' + status);
}
});
}
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;
document.getElementById('total').innerHTML = total + ' km';
}
</script>
</head>
<body>
<div id="map"></div>
<div id="right-panel">
<form>
Start<input class="textBox" id="pass1" type="text" maxlength="30" /> <br>
End<input class="textBox" id="pass2" type="text" maxlength="30" />
<input type = "button" id="button" name="button" value="search" onclick =
"SearchAddress()"/>
</form>
<p>Total Distance: <span id="total"></span></p>
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyBtQt_1BqPPuSdIbXTuYW9I8yNUGIItPuk&callback=initMap">
</script>
</body>
</html>`

<script type="text/javascript">
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var geocoder;
var moveloc1 = {lat: 55, lng: -7.3};
var moveloc2 = {lat: 55, lng: -7.1};
function SearchAddress()
{
console.log("error checker3");
var locate1 = document.getElementById("pass1").value;
var locate2 = document.getElementById("pass2").value;
console.log(locate1);
console.log(locate2);
// adress must be defined
geocoder.geocode( { 'pass1': adress}, function(results, status)
{
if (status == 'OK')
{
map.setCenter(results[0].geometry.location);
moveloc1 =
({
position: results[0].geometry.location
});
}
else
{
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
function initMap()
{
console.log("error checker1");
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: {lat: 55, lng: -7.3} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer
({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function()
{
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(moveloc1, moveloc2 , directionsService,
directionsDisplay);
console.log("error checker2");
}
function displayRoute(origin, destination, service, display)
{
service.route
({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
},
function(response, status)
{
if (status === 'OK')
{
display.setDirections(response);
}
else
{
alert('Could not display directions due to: ' + status);
}
});
}
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;
document.getElementById('total').innerHTML = total + ' km';
}
</script>

Problem:
Your problem is that you declared SearchAddress function inside of initMap function and you tried to access it from global scope (in the HTML element), which is impossible.
Explanation:
In fact a local functions and local variables can't be accessed from the global scope or from other functions. Note that in HTML elements events you can only access functions declared in the global windowscope.
You need to declare it in the global scope so you can access it from all functions and from HTML elements.
Note:
You need to fix that problem with all your functions declarations in your code.

Related

How to select mode in Google map via radio buttons instead of dropdown?

I currently have an application which routes the user between current location and a set destination. The user can alternate between 2 travel modes (driving/transit) - using a dropdown selection.
I want to change how the user selects the travel mode from a dropdown to radio buttons instead. However, unsure as to how I can alter my javascript & I have searched for a way to do so with no luck.
HTML for radio buttons & existing(working) select dropdown:
<div class="switch">
<input name="radio" type="radio" value="DRIVING" id="optionone" checked>
<label for="changemode-driving">Driving</label>
<input name="radio" type="radio" value="TRANSIT" id="optiontwo">
<label for="changemode-train" class="right">Train</label>
<span aria-hidden="true"></span>
</div>
//BELOW IS CURRENT METHOD OF HOW USER CHANGES TRAVEL MODE
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
Javascript:
<script>
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
var tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: tp
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
});
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
}, function() {
handleLocationError(true, markerme);
});
} else {
// Browser doesn't support Geolocation
window.alert('Geolocation is not supported');
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pos) {
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: pos, // Haight.
destination: {lat: 50.796358,lng: -1.063816}, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode],
transitOptions: {
modes: ['RAIL'],
arrivalTime: new Date(1489242600000),
routingPreference: 'FEWER_TRANSFERS'
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: true
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Try this code. There is a way to assign a listeners to the radio:
document.getElementsByName('radio').forEach(function(el){
el.addEventListener('click', function() {
alert($(this).val())
});
})
And a way how to get value:
var selectedMode = "";
var radios = document.getElementsByName('radio')
radios.forEach(function(element) {
if(element.checked){
selectedMode = element.value;
}
})
Please note if you'll use jQuery it could be simpler:
Anyway there working code is like this;
<script>
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
var tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: tp
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
document.getElementsByName('radio').forEach(function(el){
el.addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
});
})
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
}, function() {
handleLocationError(true, markerme);
});
} else {
// Browser doesn't support Geolocation
window.alert('Geolocation is not supported');
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pos) {
//var selectedMode = document.getElementById('mode').value;
var selectedMode = "";
var radios = document.getElementsByName('radio')
radios.forEach(function(element) {
if(element.checked){
selectedMode = element.value;
}
})
directionsService.route({
origin: pos, // Haight.
destination: {lat: 50.796358,lng: -1.063816}, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode],
transitOptions: {
modes: ['RAIL'],
arrivalTime: new Date(1489242600000),
routingPreference: 'FEWER_TRANSFERS'
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: true
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}

Asp.net using javascript, I have taken from Google maps how to save data to the database

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDX1D37MapC2HfewVE0T3MXcUT4bstvHq8&callback=initMap" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 15,
center: latlng,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById("mapContainer"), mapOptions
);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
// city data
alert(city.short_name + " " + city.long_name)
}
else {
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Your Location"
});
});
}
</script>
2-3 hours, I'm looking on the internet and I try, but I did not get results. I'm trying another code block, latitude and longitude can save the database. This is not just what I wanted, and I want to save the city formatted address.
I opened issue in another forum, not responding.
I need a lot of help. Code could bring up here. This issue of homework project.

How to add pins to google map using jQuery and JSON

I am trying to add pins to a Google Map using postcodes stored in a Google Sheet. So far I have been able to access to the Postcodes in the spreadsheet using JSON:
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v) {
var data = $('<div class="listing">').append('<h4 id="bandb">' + v.gsx$postcode.$t + '</h4>');
$('body').append(data);
});
});
I am also able to add pins to a Google Map using the postcodes.
Example: http://codepen.io/aljohnstone/pen/eJOyrP
I am having trouble combining the two. I would like the postcodes variable in the Codepen to take the postcodes from my Google Sheet.
Working example using the Google Maps Javascript API v3:
$(document).ready(function() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: {
lat: 54,
lng: -3
},
zoom: 5
});
var i;
var postcodes = [];
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v) {
postcodes.push(v.gsx$postcode.$t);
});
}).done(function() {
map.setCenter(new google.maps.LatLng(54.00, -3.00));
map.setZoom(5);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < postcodes.length; i++) {
geocoder.geocode({
'address': "" + postcodes[i]
}, (function(i) {
return function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: postcodes[i]
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}
})(i));
}
});
});
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<div id="map_canvas"></div>
Try this
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false" type="text/javascript"></script>
<div id="map_canvas" style="width: 600px; height: 350px"></div>
<script type="text/javascript">
$(document).ready(function()
{
var geocoder = new GClientGeocoder();
var map = new GMap2(document.getElementById("map_canvas"));
var i;
var postcodes = [];
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v)
{
postcodes.push(v.gsx$postcode.$t);
});
}).done(function()
{
map.setCenter(new GLatLng(54.00, -3.00), 5);
for (i = 0; i < postcodes.length; i++) {
geocoder.getLatLng(postcodes[i] + ', UK', function(point) {
if (point) {
map.addOverlay(new GMarker(point));
}
});
}
});
});
</script>
Working example http://codepen.io/snm/pen/eJOVMY?editors=101

Going over quota on Google Maps Api

So I am trying to make a simple application that will allow the user to search for restaurants and have the results show as markers on the map and as text below. The results object that returns from the textSearch doesn't provide detailed information like: phone number, pictures, etc. So i decided to create an array of place id's pushed from the results object, get the place details for each id, then push that into an array. The problem I get is a message from google saying I'm over my quota and I think it's because I'm requesting the place details for every single search result.
Is there a way I can request the place details only for the marker I click? Or is there a better solution to my problem? Thank you in advance for your help.
<!DOCTYPE html>
<html>
<head>
<title>gMap test</title>
<style type="text/css">
#map-canvas{
height:500px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
function performSearch(){
var locationBox;
var address = document.getElementById("address").value;
var searchRadius = metricConversion(document.getElementById("radius").value);
//gMaps method to find coordinates based on address
geocoder.geocode({'address':address}, function(results,status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map:map,
position: results[0].geometry.location
});
var latitude = results[0].geometry.location.A;
var longitude = results[0].geometry.location.F;
locationBox = new google.maps.LatLng(latitude, longitude);
}else{
errorStatus(status);
return;
}
//search request object
var request = {
query: document.getElementById('keyword').value,
location: locationBox,
radius: searchRadius,
//minPriceLvl: minimumPrice,
//maxPriceLvl: maximumPrice,
types: ["restaurant"]
}
//search method. sending request object and callback function
service.textSearch(request, handleSearchResults);
});
};
var latLngArray = [];
var placeIdArray = [];
//callback function
function handleSearchResults(results,status){
if( status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
placeIdArray.push(results[i].place_id)
latLngArray.push(results[i].geometry.location);
};
for(var j = 0; j<placeIdArray.length; j++){
service.getDetails({placeId: placeIdArray[j]},getDetails)
};
}
else{errorStatus(status)};
};
var detailedArray = [];
function getDetails(results,status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
detailedArray.push(results);
for(var i = 0; i<detailedArray.length; i++){
createMarker(detailedArray[i],i);
}
}
else{
errorStatus(status)
};
}
//array of all marker objects
var allMarkers = [];
//creates markers and info windows for search results
function createMarker(place, i) {
var image = 'images/number_icons/number_'+(i+1)+'.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
html:
"<div class = 'markerPop'>" + "<h3>" + (i+1) + ". " + place.name + "</h3><br>" + "<p>Address: "
+ place.formatted_address + "</p><br>" + "<p> Price Range: "+ priceLevel(place.price_level)
+ "</p>" + "</div>",
icon: image
});
allMarkers.push(marker);
marker.infowindow = new google.maps.InfoWindow();
//on marker click event do function
google.maps.event.addListener(marker, 'click', function() {
//service.getDetails({placeId: placeIdArray[j]},getDetails)
//sets infowindow content and opens infowindow
infowindow.setContent(this.html);
infowindow.open(map,this);
});
//create new bounds object
var bounds = new google.maps.LatLngBounds();
//iterates through all coordinates to extend bounds
for(var i = 0;i<latLngArray.length;i++){
bounds.extend(latLngArray[i]);
};
//recenters map around bounds
map.fitBounds(bounds);
};
var map;
var service;
var geocoder;
var infowindow;
function initialize(location){
var mapOptions = {
center: new google.maps.LatLng(37.804, -122.271),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
service = new google.maps.places.PlacesService(map)
infowindow = new google.maps.InfoWindow();
};
$(document).ready(function(){
initialize();
$('#search').on('click', function(){
removeMarkers();
performSearch();
});
});
//::::::Random Functions:::::::
//Clears all markers between searches
function removeMarkers(){
for(var i = 0; i<allMarkers.length;i++){
allMarkers[i].setMap(null);
};
};
//converts miles to meters for search object
function metricConversion(miles){
var meters;
meters = miles * 1609.34;
return meters;
}
//converts number value to $ sign
function priceLevel(number){
var moneySigns = ""
for(var i =0;i<=number;i++){
moneySigns += "$";
};
return moneySigns;
}
//errors for search results
function errorStatus(status){
switch(status){
case "ERROR": alert("There was a problem contacting Google Servers");
break;
case "INVALID_REQUEST": alert("This request was not valid");
break;
case "OVER_QUERY_LIMIT": alert("This webpage has gone over its request quota");
break;
case "NOT_FOUND": alert("This location could not be found in the database");
break;
case "REQUEST_DENIED": alert("The webpage is not allowed to use the PlacesService");
break;
case "UNKNOWN_ERROR": alert("The request could not be processed due to a server error. The request may succeed if you try again");
break;
case "ZERO_RESULTS": alert("No result was found for this request. Please try again");
break;
default: alert("There was an issue with your request. Please try again.")
};
};
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="searchBar">
<h3>search options</h3>
Location:<input type="text" id="address" value="enter address here" /><br>
Keyword<input type="text" id="keyword" value="name or keyword" /><br>
Advanced Filters:<br>
Search Radius:<select id="radius">
<option>5</option>
<option>10 </option>
<option>15 </option>
<option>20 </option>
<option>25 </option>
</select>miles<br>
<div id="minMaxPrice">
Min Price<select id="minPrice">
<option>$</option>
<option>$$</option>
<option>$$$</option>
<option>$$$$</option>
</select>
Max Price<select id="maxPrice">
<option>$</option>
<option>$$</option>
<option>$$$</option>
<option>$$$$</option>
</select>
</div>
<input type="button" id="search" value="Submit Search"/><br>
</div>
<div id='searchResults'>
</div>
</body>
</html>
The radarSearch example in the documentation requests the details of the marker on click.
code snippet:
var map;
var infoWindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-33.8668283734, 151.2064891821),
zoom: 15,
styles: [{
stylers: [{
visibility: 'simplified'
}]
}, {
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'best view'
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ffff00',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var htmlStr = "<b>"+result.name+"</b><br>";
if (result.website) htmlStr += "<a href='"+result.website+"'>"+result.website+"</a><br>";
if (result.adr_address) htmlStr += result.adr_address+"<br>";
infoWindow.setContent(htmlStr);
infoWindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<div id="map-canvas"></div>
I had the same issue some time ago. The geocoding function by google is done in order to avoid the user executing it on a large set of data (and then, avoid you to get a large amount of geocoded address easily).
My solution was to execute the geocoding function only when the user choose a particular place, and then, display this particular data (handled by the click on the pin).
I think it would be very useful to initiate a jsfiddle with a working version of your code.
Basically on your function :
google.maps.event.addListener(marker, 'click', function() {
//Execute geocoding function here on marker object
//Complete your html template content
infowindow.setContent(this.html);
infowindow.open(map,this);
});

Firing multiple javascript functions on page load

I have managed to create a simple map with a marked route between 2 destinations. Additionally, I need to pull the distance value and then do some basic math with it (multiply it by 2). It all works, but not on page load. More precise, map is displayed on page load as well as distance, but distance value doesn't get pulled and it doesn't get multiplied by 2. I have managed to make it work on mouse move, but it's not the perfect replacement.
Here is the code:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&region=US"></script>
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="http://www.pengoworks.com/workshop/jquery/calculation/jquery.calculation.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
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.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Houston',
destination: 'Dallas',
travelMode: google.maps.DirectionsTravelMode.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.
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
function stripint() {
var val = $('[jsdisplay=distance]').text(); // get text content of <span jstcache="7">
// Replace using regex instead of strings, to catch more than the first match
val = val.replace(/\./g, "");
val = val.replace(/,/g, ".");
val = val.replace(/_/g, ",");
$('#dist').val(val);
}
function recalc() {
$("[id^='total_price_ht']").calc(
// the equation to use for the calculation
"di * 10", {
bind: "keyup",
di: $("[id^='dist']")
}, function(s) {
// return the number as a dollar amount
return "$" + s.toFixed(2);
});
}
$('#content').mousemove(function() {
stripint();
recalc();
});
stripint();
recalc();
});
</script>
</head>
<body>
<div id="content">
<p>Distance: <span id="total"></span>
</p>
<input type="text" value="0" name="dist" id="dist" />
<div id="total_price_ht_0" class="price">$0.00</div>
<div id="map-canvas" style="width:100%; height:500px"></div>
<div id="directionsPanel" style="width:100%; height:auto"></div>
</div>
</body>
first of all you don't need to use $(document).ready() because you already bind the initialize function to the window onLoad event google.maps.event.addDomListener(window, 'load', initialize);
what you want is wait until the directions and distance are calculated, you don't really need to read it from the directionsPanel, you can read whatever you need directly from the API response.
use the callback in calcRoute like this:
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
dist = response.routes[0].legs[0].distance.text;
stripint(dist);
recalc();
}
});
you also need to add the dist argument to you strprint:
function stripint(val) {
// Replace using regex instead of strings, to catch more than the first match
val = val.replace(/\./g, "");
val = val.replace(/,/g, ".");
val = val.replace(/_/g, ",");
$('#dist').val(val);
}
so your new code doesn't use document.ready and calculates the price immediately when the API responds.
the new <script> tag:
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
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.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Houston',
destination: 'Dallas',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
dist = response.routes[0].legs[0].distance.text;
stripint(dist);
recalc();
}
});
}
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.
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
function stripint(val) {
// Replace using regex instead of strings, to catch more than the first match
val = val.replace(/\./g, "");
val = val.replace(/,/g, ".");
val = val.replace(/_/g, ",");
$('#dist').val(val);
}
function recalc() {
$("[id^='total_price_ht']").calc(
// the equation to use for the calculation
"di * 10", {
bind: "keyup",
di: $("[id^='dist']")
}, function (s) {
// return the number as a dollar amount
return "$" + s.toFixed(2);
});
}
here is no need to have two tags; you can put everything inside one. Some of your functions use jQuery selectors, try to put all of them inside the $(document).ready(), this will guarantee that all the selected elements are available by the time they are called:
$(document).ready(function(){
//Insert your functions with selectors here
});
Here is the rearranged code with everything inside document.ready: http://jsbin.com/iqejiy/1/edit
Hope it helps.
i think you are missing document.ready() here.

Categories