How to perform a quality check during kmllayer load - google-maps

I am using kmllayers from the standard Google Dev site:
var ctaLayer = new google.maps.KmlLayer({
url: 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml'
});
ctaLayer.setMap(map);
How do you do error checking? In my example I have url with a get parameter to get a filtered response from a database whose return is a kml.
If I get a null response or a kml with no data, I want to redirect the page. How do I perform the check?

Per the documentation on KmlLayer, the KmlLayerStatus can be retrieved from the KmlLayer:
var ctaLayer = new google.maps.KmlLayer({
url: 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml'
});
google.maps.event.addListener(ctaLayer,'status_changed', function() {
if (ctaLayer.getStatus() != OK) {
alert("error loading KML, status="+ctaLayer.getStatus());
}
}
ctaLayer.setMap(map);

Related

google maps api, get directions not passing full link and No 'Access-Control-Allow-Origin'

So I have a map and when user clicks on any marker I want to get a json. All variables have a value and when I manually put them in browser I get an response. At the moment I get:
XMLHttpRequest cannot load
https://maps.googleapis.com/maps/api/directions/json?origin=53.5411328&-2.1114581&destination=53.54027.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'my url of course' is therefore not allowed
access.
And the link looks like this:
https://maps.googleapis.com/maps/api/directions/json?origin=53.541111&-2.1114894&destination=53.54027
while it should be:
https://maps.googleapis.com/maps/api/directions/json?origin=53.541111,-2.1114894&destination=53.54027,-2.1121799&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65
Code:
marker.addListener('click', function() {
var destinationLat = marker.getPosition().lat();
var destinationLng = marker.getPosition().lng();
console.log(lat);
console.log(lng);
console.log(destinationLng);
console.log(destinationLat);
var test = $.getJSON('https://maps.googleapis.com/maps/api/directions/json?origin='+lat+'',''+lng+'&destination='+destinationLat+'',''+destinationLng+'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65', function(data) {
console.log(test);
});
console.log(test);
});
}
The mistake's in this line:
var test = $.getJSON('https://maps.googleapis.com/maps/api/directions/json?origin='+lat+'',''+lng+'&destination='+destinationLat+'',''+destinationLng+'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65', function(data) {
That should be:
var test = $.getJSON('https://maps.googleapis.com/maps/api/directions/json?origin='+lat+','+lng+'&destination='+destinationLat+','+destinationLng+'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq65', function(data) {
In order to avoid the CORS headers issue in your JavaScript code you should use a built-in Directions service of Maps JavaScript API.
https://developers.google.com/maps/documentation/javascript/directions
Replace your AJAX call with something similar to
directionsService.route({
origin: new google.maps.LatLng(lat,lng),
destination: new google.maps.LatLng(destinationLat,destinationLng),
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
//Process response here
} else {
window.alert('Directions request failed due to ' + status);
}
});
Take a look at examples
https://developers.google.com/maps/documentation/javascript/examples/directions-simple
I hope this helps!

Google Maps API: No 'Access-Control-Allow-Origin' header is present on the requested resource

I've seen this question asked by multiple people, none of the answers have worked for me.
I'm trying to make an API call to the google maps api with react/axios.
This is my get request:
componentDidMount() {
axios({
method : 'get',
url : `http://maps.googleapis.com/maps/api/js?key=${key}/`,
headers: {
"Access-Control-Allow-Origin": '*'
"Access-Control-Allow-Methods": 'GET',
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
This is the error msg:
XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/js?
key=xxxxxxxxx/. Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the
requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I've read the article con CORS that everyone else points to
https://www.html5rocks.com/en/tutorials/cors/
but I can't find an answer to my problem there.
https://maps.googleapis.com/maps/api doesn’t support getting requests from frontend JavaScript running in web apps in the way your code is trying to use it.
Instead you must use the supported Google Maps JavaScript API, the client-side code for which is different from what you’re trying. A sample for the Distance Matrix service looks more like:
<script>
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
},…
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
And here’s an example for using the Place Autocomplete API using the Places library:
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
...
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
async defer></script>
Using the Maps JavaScript API like that—by way of a script element to load the library, then using the google.maps.Map and other google.maps.* methods—is the only supported way to make requests to the Google Maps API from frontend JavaScript code running a browser.
Google intentionally doesn’t allow access to the Google Maps API by way of requests sent with axios or AJAX methods in other such libraries, nor directly with XHR or the Fetch API.

From API to vector layer openlayers JSON

If you want to import a json file in your system to a vector layer, is as easy as:
var restaurantsold = new ol.layer.Vector({
title: 'b_layer',
source: new ol.source.Vector({
url: 'restaurantjson.geojson',
format: new ol.format.GeoJSON()
}),
});
And I can add that layer directly to the map. But if I try to make a call to an API, I can't display it in the map, my best try has been this:
var restaurants;
$.ajax({
type: "GET",
url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita",
dataType:"json",
success:function(data){
console.log(data)
restaurants = data;
$(restaurants).each(function(index, value) {
console.log(value.address);
});
}
});
var resta2 = new ol.layer.Vector({
title : "Resta2",
source: new ol.source.Vector(restaurants)
});
And I can't find a proper solution anywhere for this, thanks for your help!
EDIT:
at the end the problem was that it gets a JSON file, and openlayers wants an GeoJSON file.. my way to solve it was to convert it to GeoJSON following this:
https://gis.stackexchange.com/questions/73756/is-it-possible-to-convert-regular-json-to-geojson
The Restaurant data might not be available at all when you are creating the vector layer since you are making an Ajax Call.
So convert the GeoJSON to collection of ol.Feature objects using ol.format.GeoJSON readFeatures() method. Then add it vector source using addFeatures() method.
Fix :
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON()
})
var restaurantsold = new ol.layer.Vector({
title: 'b_layer',
source : vectorSource
});
$.ajax({
type: "GET",
url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita",
dataType:"json",
success:function(data){
// If response is valid
var geojsonFormat = new ol.format.GeoJSON();
// reads and converts GeoJSon to Feature Object
var features = geojsonFormat.readFeatures(data);
vectorSource.addFeatures(features);
}
});

How do I upload a .gpx file from localhost to google maps (v3) ?

I'm new to the Google Maps API and I'm working on localhost.
I want to add the ability for a user to upload their .gpx file and visualize it on the Google Map.
I've found this AJAX function wich works fine when I hardcode the .gpx file, but when I try to import the file from my computer, I got a grey screen for short second which then disappears.
Any idea or solution for this problem is more than welcome.
Thanks in advance.
function get_file() {
var fileInput = document.getElementById("file_upload");
var filename = fileInput.value;
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
loadGPXFileIntoGoogleMap(map, filename);
}
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: "xml",
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour("#ff0000"); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
There is no way to access filesystem from JavaScript.
This is a security issue. To resolve your issue I can see only one option: You should have server-side functionality that will temporary store user uploaded data. And then you can load user defined .gpx files from server.

Google maps kml layer

my code is:
var ctaLayer = new google.maps.KmlLayer(
'http://.../per1.kml',
{suppressInfoWindows: true});
ctaLayer.setMap(map);
var info_percurso = new google.maps.InfoWindow({
content: 'hi'
});
google.maps.event.addListener(ctaLayer, 'click', function() {
info_percurso.open(map,ctaLayer);
alert("dd");
});
this is possible?
this code doesn't work...but the operation is possible?
I need to create my own infoWindow for database queries
make sure the kml is being served. You may need to add the kml MIME type to the server.
application/vnd.google-earth.kml+xml