google api key as a variable - javascript

<script src="jquery.js"></script>
<script>
$.get('http://localhost/ajax_send_key.php',function (data){
api_key = data;
});
</script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key= - my api key - &libraries=places">
// this one work
// src="https://maps.googleapis.com/maps/api/js?key={api_key}&libraries=places">
// Google Maps JavaScript API error: InvalidKeyMapError
// src="https://maps.googleapis.com/maps/api/js?key=" + api_key + "&libraries=places">
// TypeError: Cannot read properties of undefined (reading 'Autocomplete') at initialize
</script>
<script>
lat = '';
function initialize() { // google places wohl für ortseingabe und dann vorschläge
var input = document.getElementById('in');
var places = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var lat = place.geometry.location.lat();
});
return (lat);
}
window.addEventListener('load', initialize);
</script>
<html>
input
<input id='in' type = 'text' STYLE = 'width: 220px' ;></input>
</html>
hello,
I have a problem with my Api Key, when I try to use it as a variable. how do I put it into the src="https://maps.googleapis.com/maps/api/js?key=
It works if it is not a variable.
thanks georg

Don't create the script tag on load. Wait for the key response to come back first before creating it, and then you can create the src appropriately. You'll also have to wait for Google's script to load before calling initialize.
$.get('http://localhost/ajax_send_key.php',function (data){
const script = document.body.appendChild(document.createElement('script'));
script.src = `https://maps.googleapis.com/maps/api/js?key=${data}&libraries=places`;
script.addEventListener('load', initialize);
});

Related

Angular 10 | Google adwords conversion code in head | How to call gtag_report_conversion from component

I have added google adwords conversion code to the head of my index.html:
<!-- Global site tag (gtag.js) - Google Ads: 0000000-->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-0000000"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-0000000');
</script>
<!-- Event snippet for 0000000 conversion page
In your html page, add the snippet and call gtag_report_conversion when someone clicks on the chosen link or button. -->
<script>
function gtag_report_conversion(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-0000000/0000000-0000000',
'event_callback': callback
});
return false;
}
</script>
The conversion should be counted when a user successfully registers. For this I need to wait for the success message in my register user api endpoint, which is called in a component:
this.http.post<any>(apiEndpoint, sendData).subscribe(data => {
console.log(data);
if (data['error']) {
this.regError = data['errortxt'];
} else {
this.regError = "";
this.dataService.REG_AUTH = data['data']['token'];
localStorage.setItem('regauth', data['data']['token']);
// Adwords Conversion
gtag_report_conversion(url);
this.navigation.loadView(this.navigation.getView('3').name);
}
}, error => {
console.log(error.json());
});
It tells me Cannot find name gtag_report_conversion(url);
Any ideas? Somehow I need to import the function from index.html?
Just use gtag in your component directly:
declare var gtag;
And in your Adwords Conversion call:
this.regError = "";
this.dataService.REG_AUTH = data['data']['token'];
localStorage.setItem('regauth', data['data']['token']);
// Adwords Conversion
gtag('event', 'conversion', {
'send_to': 'AW-0000000/0000000-0000000'
});
this.navigation.loadView(this.navigation.getView('3').name);

I am unable to get Coordinates from ajax to the google map script

This my places.php file Here I am getting my coordinates from the database, I have checked this by echoing it's just fine, Also my connection to the database is just fine. Here I have made a self-executing function that repeats itself in an infinite loop and whenever the values will be changed or updated in the database my marker position will also updated. The code is very simple but looks like my ajax success variables aren't working.
include 'connection.php';
$myque = mysqli_query($con, 'Select * from places where id=1');
$gtloc = mysqli_fetch_array($myque);
$lati = $gtloc['lati'];
$long = $gtloc['longi'];
echo lati.",".$long;
//echo $long;
}
Here I am receiving the ajax success response and assigning it to a variable but it doesn't work.
Inserting Direct Coordinates shows the map but I need to make the marker responsive to database coordinates without refreshing the page. Inserting my variable to lat & long just and the map totally disappears
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function test(){
//ajax call goes here
$.ajax({
url: "places.php",
type: "GET",
async: true,
data: {"id": 1},
success : function(value){
//alert("RESPONSE");
var data = value.split(",");
var latitude = (data[0]);
var longitude = (data[1]);
}
});
window.setTimeout(function(){
test();
}, 1500);
}
$(document).ready(function(){
test();
});
</script>
<script>
function initMap() {
var uluru = {lat: latitude , lng: longitude };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
</head>
<body>
<script></script>
<h2>My Places</h2>
<div id="map" style="height: 700px;width: 100%;"></div>
<!--map script -->
<!-- / Map Script-->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBYBZxCetgqbsCQU3mxZ622GwNdSglEVN4&callback=initMap"></script>
</body>
</html>
The issue is that those are string values. Try to make then lat/long float variables...
var lat = parseFloat(latitude);
var long = parseFloat(longitude);
In your example:
success : function(value){
//alert("RESPONSE");
var data = value.split(",");
var latitude = (data[0]);
var longitude = (data[1]);
}
Just add parseFloat like this:
var latitude = parseFloat(data[0]);
var longitude = parseFloat(data[1]);
I think it would solve it.

google.maps.places is undefined

I have a website that loads 3 seperate "views" of a location via Google Maps, Street and Places.
Please see my code below:
I have finally gotten Maps and Street view to work properly but am struggling a bit with this one.
I have a tab that displays the same as map but with places added.
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
<script type="text/javascript">
var myLattitude = <?php echo $data["lattitude"]; ?>;
var myLongitude = <?php echo $data["longitude"]; ?>;
var poiMap;
var infowindow;
function initializePoi() {
var poiCentre = new google.maps.LatLng(myLattitude, myLongitude);
poiMap = new google.maps.Map(document.getElementById('poi-canvas'), {
center: poiCentre,
zoom: 15
});
var request = {
location: poiCentre,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(poiMap);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: poiMap,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(poiMap, this);
});
}
Now This initializes properly but the console throws the following error:
TypeError: google.maps.places is undefined
I just want to know why I get this error, I like having clean errorless code.
The places do actually show up properly and everything.
You should add the option libraries=places in the Google API URL
In your case you should replace the following:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
With this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Look at the end of the src=""
Now, you have to use https instead of http.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Everything else is same as previous answer mentioned.
Since the top answer addresses the vanilla version, this is for those using google-maps-react:
add libraries: ['places'] to your GoogleMapReact Component:
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey, libraries: ['places'] }}
...
/>
If you are using React.
import { Wrapper as MapsWrapper } from "#googlemaps/react-wrapper";
// Note libraries prop.
<MapsWrapper apiKey={'YOUR_API_KEY'} libraries={['places']}>
<ChildComponent />
</MapsWrapper>

Correct way to parse this JSON and use it with D3

I'm using random user generator to get the JSON data:
http://randomuser.me/
I make a call everytime I click a button, so the zip code I get in return I use it to do a geocoder in google maps API and get a latitude and longitude. Until that it has work very well but I don't know how to use it on Google Maps. I'm trying to create D3 circles and there are two ways to do this:
1.- Using the drawing shapes from Google Maps API:
https://developers.google.com/maps/documentation/javascript/shapes#circles
2.- Using the custom overlay from Google Maps API:
https://developers.google.com/maps/documentation/javascript/customoverlays
I need to do it with the overlay and draw the graphics with D3 like in this example:
http://bl.ocks.org/mbostock/899711
So my doubts are:
1.- How can I use D3 to use the latitude and longitude and load them? In the example they load JSON from the directory but here I'm using remote data. Should I considered a JSON parse or a String or any other?
2.- What is the correct way to write this as a clean code? And why?
Thank you in advance
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/d3.v3.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(16.4706001, -33.6728973),
zoom:3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="button">
<button id="loadbutton">Click to Load</button>
</div>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
script.js
var randomuserURL = 'http://api.randomuser.me/';
var myButton = document.getElementById('loadbutton');
myButton.onclick = loadAJAX;
var lat = '';
var lng = '';
var zipcode;
var geocoder = new google.maps.Geocoder();
function loadAJAX () {
$.ajax({
url: randomuserURL,
dataType: 'json',
success: function(data){
zipcode = data.results[0].user.location.zip;
latlng();
}
});
}
function latlng () {
geocoder.geocode( { 'address': zipcode}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
console.log('Latitude: ' + lat + ' Logitude: ' + lng);
}
You basically have everything you need.
There's no need to load a "local" file -- d3.json will take any URL as its first argument. The only problem you may run into are browser security restrictions. In that case JSONP may help.
If your code works for you, it should be fine. Honestly, you have so little code that it really doesn't matter.

Google Map API v3 - Ajax (Javascript + Jquery) GET issue

I am trying to make the map load markers - pulled in from an xml file. It currently does this perfectly. However I also want the map to reload new markers based upon the month passed through from a hyperlink.
When the 'global_month' variable is changed via hyperlink the ajax request fires and the 'data_array' should be repopulated with the new data based upon the date passed to the 'if' statement later on. However it reuses the 'data_array' contents, and doesn't fill it with new data.
I have tried resetting the 'global_month' via 'global_month = []' in the 'change_date_range' function, however - the array doesn't seem to be refilled. I have spent 3 hours trying to work out where I am going wrong, but cannot. Can anyone help? Also is there a more efficient way of doing this?
Thank you very much for you time!
/////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
});
var global_month = 6;
function refetch()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
};
var data_array = [];
var empty_holder;
var empty_month;
var info_date;
var address1;
var address2;
var town;
var county;
var postcode;
var lat;
var lon;
var male_pass_percentage1;
var male_pass_percentage;
var female_pass_percentage1;
var female_pass_percentage;
var the_new_date;
var infowindow;
var xml_contents;
function parseXml(xml)
{
$(xml).find("test_center").each(function() // look for all of the test centers
{
center_name = $(this).attr('name');
address1 = $(this).find('address1').text();
address2 = $(this).find('address2').text();
town = $(this).find('town').text();
county = $(this).find('county').text();
postcode = $(this).find('postcode').text();
lat = $(this).find('lat').text();
lon = $(this).find('lon').text();
$(this).find("date_info").each(function()
{
info_date = $(this).attr('date');
empty_month = $(this).find('month').text();
male_pass_percentage = $(this).find('male');
male_pass_percentage = male_pass_percentage.find('pass_percentage').text();
female_pass_percentage = $(this).find('female');
female_pass_percentage = female_pass_percentage.find('pass_percentage').text();
if(empty_month == global_month){
data_array.push([lat,lon,center_name,info_date,male_pass_percentage,female_pass_percentage]);
}
});
});
}
function change_date_range(the_new_date){
global_month = the_new_date;
refetch();
init();
};
</script>
<script>
function init() {
var options = {
zoom: 5,
center: new google.maps.LatLng(55.3781, -3.4360),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var places;
places = null;
var map = new google.maps.Map(document.getElementById('map'), options);
var bounds = new google.maps.LatLngBounds();
var places = data_array;
var temp_location;
for (var i = 0; i < places.length; i++) {
temp_location = new google.maps.LatLng(places[i][0], places[i][1])
// Adding the markers
var marker = new google.maps.Marker({
position: temp_location,
map: map,
title: places[i][2]
});
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(i, marker) {
// Creating the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
// Check to see if we already have an InfoWindow
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow
infowindow.setContent(places[i][2] + "<br />" + global_month + "<br />" + places[i][3] + "<br /><br />Male: " + places[i][4] + "%<br />Female: " + places[i][5] + "%");
// Tying the InfoWindow to the marker
infowindow.open(map, marker);
});
})(i, marker);
// Extending the bounds object with each LatLng
bounds.extend(temp_location);
}
// Adjusting the map to new bounding box
map.fitBounds(bounds)
};
</script>
</head>
<body onload="init()">
<div id="map" style="width:800px;height:600px"></div>
click
</body>
</html>
/////////////////////////////////////////////////////////////
XML file (small part of):
http://tinypaste.com/198889bb
You're not clearing out the data_array array...you just continue to add to it. Why don't you add data_array = []; to the beginning of the parseXml function
edit: you should also clear the markers that are already placed...a good way to make that easy is that when you add markers, hold them in an array, then you can loop through it, setting the map attribute of each to null:
for (x=0;x<markers.length;x++) {markers[x].setMap(null);}

Categories