How to only read Google maps API key in production - javascript

I'm working on a React application that uses Google maps. I've been working on it in development mode only and would like to add the API key now when I push it to production.
I'm loading the Google Maps script like the code below and it seems to work, but I would like to only read from my .env and use the API key in production, not when I develop locally on http://localhost:3000/, etc. Does anyone know if there is a simple way to do this?
if (!scriptElementExists) {
// Create a new script tag
const scriptElement = createScriptElement(
'google-maps',
`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_KEY}&callback=${googleMapsData.scriptCallbackName}`
);
// Append the script to the document
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
My .env
# Google Maps Api Key
REACT_APP_GOOGLE_MAPS_KEY={{API_KEY}}
Thanks beforehand!
And please ask if I've made myself clear.

If you are using Create React App you can use process.env.NODE_ENV.
It is set automatically to development or production.
https://create-react-app.dev/docs/adding-custom-environment-variables

Related

How can I use a client ID and secret to access the Google Maps JS API, instead of an API key?

I'm trying to add a Google Map to our app via Google's JS Maps API. I'm following the documentation here. I've installed #googlemaps/js-api-loader via yarn, and am now trying to instantiate a loader:
import { Loader } from "#googlemaps/js-api-loader";
const loader = new Loader({
// ???
})
The problem is, the docs tell me to provide an API key in this initializer. But we don't use an API key, we use an app/client ID and secret for this project.
How am I meant to use the Google Maps JS API in this way with an ID and secret, not an API key? I see this question and this question, but neither actually tells you to do it. Also, this documentation shows you how to use a client ID when you're using a <script> tag, but I would prefer to load via the yarn package.
Is there a way I can achieve this?
The client param is supported. https://googlemaps.github.io/js-api-loader/interfaces/loaderoptions.html#client
import { Loader } from "#googlemaps/js-api-loader";
const loader = new Loader({
client
})
If this doesn't work, please open a bug at https://github.com/googlemaps/js-api-loader

Where to insert google map api key in wordpress theme

in my wordpress website i am getting this error for google map
Google Maps API error: MissingKeyMapError
now i have google map api key but i don't know where to insert it, i am not using google map plugin, i am using theme that contain build in google map, what i found now is the reference to google map javascript file that contain this code
var tl_geocoder;var $tl_map;var $tl_marker=false;jQuery(function(a){jQuery(document).ready(function(c){tl_geocoder=new google.maps.Geocoder();c(document).on("click",".layers-check-address",function(f){f.preventDefault();$tl_map=c(this).closest(".layers-map");var g=c(this).closest(".layers-content").find('input[id$="google_maps_location"]').val();var d=c(this).closest(".layers-content").find('input[id$="google_maps_long_lat"]').val();$tl_map.data("location",g.toString());$tl_map.data("longlat",d.toString());b(c)});b(c)});function b(d){var c=false;jQuery(".layers-map").each(function(){var h=d(this);var k=(undefined!==h.data("longlat"))?h.data("longlat"):null;if(null!==k){var l=k.split(",");var m=l[0];var e=l[1]}else{var m="-34.397";var e="150.644"}var f=new google.maps.LatLng(m,e);var j=h.data("zoom-level");$tl_map=new google.maps.Map(h[0],{scrollwheel:false,zoom:j,center:f,mapTypeId:google.maps.MapTypeId.ROADMAP});var g=!d(this).closest("div.layers-contact-widget").hasClass("no-infobox");if(undefined!==h.data("longlat")){var n=new google.maps.LatLng(m,e);$tl_map.setCenter(f);$tl_marker=new google.maps.Marker({map:$tl_map,position:n,zIndex:google.maps.Marker.MAX_ZINDEX+1,icon:TL_CONF.themeurl+"/assets/images/google-marker.png"});if(!c&&g){c=true;d("body").trigger("setInfobox")}else{$tl_marker.setMap($tl_map)}}if(undefined!==h.data("location")&&$tl_marker===false){var i=h.data("location");tl_geocoder.geocode({address:i},function(p,o){if(o==google.maps.GeocoderStatus.OK){$tl_map.setCenter((p[0].geometry.location?p[0].geometry.location:f));$tl_marker=new google.maps.Marker({map:$tl_map,zIndex:google.maps.Marker.MAX_ZINDEX+1,position:(p[0].geometry.location?p[0].geometry.location:f),icon:TL_CONF.themeurl+"/assets/images/google-marker.png"});if(!c&&g){c=true;d("body").trigger("setInfobox")}else{$tl_marker.setMap($tl_map)}}})}})}}(jQuery));
but i am still not sure where to insert google map api key
IIRC, Google maps introduced the api key usage as a recent update and the theme you're using has the older version of the api, one that does not use the api key.
You should check for an update of the theme. If it is an active one, the developer should have incorporated the api key mechanism by now so that you can provide the api key directly somewhere under the theme settings (in wp-admin).
If not, you can try with any of the available Google Maps plugins. I know for a fact that some such plugins work without an api key even today, e.g. the SiteOrigin Widgets Bundle ver. 1.6.1:
https://wordpress.org/plugins/so-widgets-bundle/developers/

Cordova App launching Google App

After using the below code. App is launching the native android map showing the app with passed lat and long value.but my problem is after clicking on the nav option the 'from' is blank but 'to' should be coming as my passed value. But it is coming as blank value.
window.location = 'geo:40.765819,-73.975866'
If you are willing to use Cordova plugins, then I would suggest taking a look at the Launch Navigator plugin.
It allows you to do exactly what you want, but also allows you to launch other supported apps and even allows you to prompt the user with a list of applications to choose from.
There is an example in the documentation, showing how you can open a specific application, like Google Maps. For your convenience, I have also posted it below.
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable) {
var app;
if(isAvailable) {
app = launchnavigator.APP.GOOGLE_MAPS;
} else {
console.log("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([40.765819, -73.975866], {
app: app
});
});
In this piece of code, the user will still be given a choice to pick another app, if Google Maps is not available.
There is also an AngularJS wrapper available for this called ngCordova, installation instructions are here and documentation about the wrapper for the Launch Navigator plugin can be found here.

is it possible to embed a google web app in a third party website?

For my job, we are creating a google apps script based web app. However, our client would like to have the web app on their own personal appropriately-branded website. The problem is, from the "Web Apps and Google Sites Gadgets" page, I only see an option to embed web apps into Google Sites specifically, and can't find any info otherwise anywhere else. Does that mean that there is no way to embed into personal websites or is there a workaround that i'm not finding anywhere?
Thank you!
I use ContentService to use Apps Script as a backend.
https://developers.google.com/apps-script/reference/content/content-service
On my webpage I use a call like:
var url = "https://script.google.com/macros/s/AKfycb...vZ8SvFBRWo/exec?offset="+offset+"&baseDate="+baseDate+"&callback=?";
$.getJSON( url, function( events ) { ...
In my script:
function doGet(e){
var callback = e.parameter.callback; // required for JSONP
.
.
return ContentService.createTextOutput(callback+'('+ JSON.stringify(returnObject)+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
}

Google Analytics testing/sandbox environment?

Is there any Google Analytics testing/sandbox environment for testing your JS custom code before putting it to live system?
I don't want to use my real tracking ID to see if everything is correct on my dev. environment, neither I want to put my code untested live...
Is there any techniques or maybe some fake Analytics tracking lib I could use for testing?
The Google Analytics Debugger Chrome Extension is very helpful in testing Google Analytics code. The extension outputs the data sent to Google Analytics to the JavaScript Console Window. The days of you...waiting around...hoping/praying to see your test Pageviews in Google Analytics are over.
Below is an example of some of the output the extension prints to the JavaScript Console Window:
Track Pageview
Tracking beacon sent!
Account ID : UA-2345678-90
Page Title : About
Host Name : www.yourdomain.org
Page : /about
Referring URL : -
Language : en-us
Encoding : UTF-8
Flash Version : 11.1 r102
Java Enabled : true
Screen Resolution : 1680x1050
Color Depth : 16-bit
Ga.js Version : 5.2.4d
Cachebuster : 476867651
I believe it is possible, but you have to tell it to not use the domain when setting the cookie...
var pageTracker = _gat._getTracker("UA-12345-1");
pageTracker._setDomainName("none");
pageTracker._trackPageview();
And you probably have to use a legitimate tracker ID.
Also, be sure to see Analytics Customizations: Using a Local Server
Why don't you just create a new tracking code / profile in GA? That way you can see the results on your dev server and then switch to the real tracking number when you move to live.
I think a lot has changed since the question was asked, but I believe I should add this here just for the new visitors since it is not in the answers.
Google Analytics now has a Sandbox Account that you can create. Check out the source for the direct announcement by them.
Short instructions from the link:
If you already have a Google Analytics account, you'll need to create a new one as your "sandbox" by following these instructions:
Click Admin at the top of any Analytics page.
In the Account column, click the menu, then click Create new account.
Follow the instructions.
Source:
https://groups.google.com/forum/#!category-topic/digital-analytics-fundamentals/6EYCkNdE2No
I think it should be done with "views" in 2019.
Create views for development and production https://support.google.com/analytics/answer/1009714?hl=en
Create a custom dimension "environment" = "test" / "prod". Send it from website/app.
Create filters by custom dimension "environment" on view level https://www.bounteous.com/insights/2015/10/16/filtering-session-user-custom-dimensions-google-analytics/
Maybe for some projects filters can be done by URL instead of custom dimensions.

Categories

Resources