简体   繁体   中英

Dynamic setting of Google Maps Api Key for GMLib component

In the past it was a question about setting Google Maps Api Key for the gmlib component. The provided solution was to change the 'map.html' head element then recompile the resources (rc.cmd) and recompile the component. This is a quite static solution and sometimes it would be more convenient to set the api key dynamically at runtime eg when someone want to use different keys for different projects (api keys can be stored in some ini/property file of the projects). I think the best way would be a property for the GMMap component and a new parameter for the constructor. I searched google maps javascript api for some functionality like changing/setting api key but I didn't find any. It seems that api key has to be 'hardcoded' into the head tag of the html file and there is no javascript function to change it. (If some javascript function existed then an ExecuteScript would call it.)

Any idea how to set api key at runtime?

For example I found this link that changes the document itself: Can I change/set the Google Maps API Key dynamically from JavaScript?

How to utilize this in gmlib?

Thanks in advance.

Really, this solution is not necessary into GMLib because when you (he components) loads the HTML map from the resource file, you can changes this line (you can adds the key) by code before load it into the TWebBrowser.

You needs to add a key property in TGMMap and, into the GetBaseHTMLCode method, take into account this property.

To easy change this key, you can changes this line from the HTML code

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&libraries=weather,panoramio,geometry,drawing"></script>

by this other

<script type="text/javascript" src="https://maps.google.com/maps/api/js?%ssensor=false&libraries=weather,panoramio,geometry,drawing"></script>

And change the GetBaseHTMLCode method for this

function TCustomGMMap.GetBaseHTMLCode: string;
var
  List: TStringList;
  Stream: TResourceStream;
begin
  Result := '';

  List := TStringList.Create;
  try
    try
      Stream := TResourceStream.Create(HInstance, RES_MAPA_CODE, RT_RCDATA);
      List.LoadFromStream(Stream);
      Result := List.Text;
      Result := Format(Result, [KeyProerty]); // <== add this line
    finally
      if Assigned(Stream) then FreeAndNil(Stream);
      if Assigned(List) then FreeAndNil(List);
    end;
  except
    raise Exception.Create(GetTranslateText('No se ha podido cargar el recurso', Language));
  end;
end;

This change is not tested but this is the idea :-)

I put it into my TODO list for this week ;-)

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM