Problem Definition:
If anyhow you'd like to access google web services (like Geocoding, Directions api etc.) inside a Silverlight browser application, when you use a webclient do the http request to the service you are going to get a security exception.
This is caused by the cross-domain-policy which forbids browser clients outside of the service url to access the services. The main reason behind this is that all browser applications which try accessing a web-site can use the open seasons of that browser client. And malicious browser clients can hijack that open seasons and access user specific information, modify accounts etc.
Solution 1 - Change your way and do the request via a service on your server:
In example use a wcf service and do the request to google via that service. This is the easy way out. But in conditions this solution is not acceptable advance to the solution 2.
Solution 2 - Javascript Workaround
A silverlight application can't do a http request to the google servers but the http page containing the silverlight client can use google javascripts api to do the trick.
For achieving this follow these steps.
Step 1 - Create a notification function in your silverlight application. This will be used to notify the silverlight client when call to google javascript api returns a result.
namespace SilverlightApplication{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Page", this);
}
[ScriptableMember]
public void ServiceResult(string result)
{
//Parse the result. (result will be in json format. parse the result and do whatever needed)
}
}
}
Step 2 - Create the javascript function inside your html page which is containing the silverlight client file.
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function Geocode(parameter) {
var geocoder = new google.maps.Geocoder();
var address = parameter;
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
var control = document.getElementById("silverlightControl");
control.Content.Page.ServiceResult(JSON.stringify(results));
});
}
}
</script>
Step 3 - Trigger the javascript function from silverlight client.
HtmlPage.Window.Invoke("Geocode", "London UK");