Keep getting "Unexpected token ," with coordinates in variables - javascript

I'm trying to get the latitude and longitude from variable but I'm keep getting Unexpected token ,. I have tried to use var coordinates = 59.328615,13.485699 and var coordinates = '59.328615,13.485699' but I only got the same error. Now I'm out of ideas. What's wrong?!
var coordinate_latitude = 59.328615;
var coordinate_longitude = 13.485699;
var marker;
var gm_map;
function initialize() {
var latlong = new google.maps.LatLng(coordinate_latitude, coordinate_longitude);
var googlemaps_options = {
zoom: 18,
minZoom: 4,
maxZoom: 18,
center: latlong,
mapTypeId: google.maps.MapTypeId.SATELLITE,
streetViewControl: false
}
gm_map = new google.maps.Map(document.getElementById('google-maps'), googlemaps_options);
marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: gm_map
});
}
$(document).ready(function() {
// INITIERA GOOGLE MAPS
initialize();
});
Thanks in advance.

Don't use the ready function to initialize the map. The needs to be done in the load event once the page is rendered. It works fine for me if I remove the jquery and do this instead:
google.maps.event.addDomListener(window, 'load', initialize);
Working example

var coordinates = 59.328615,13.485699 isn't valid JS. It should be something like:
var coordinate_latitude = 59.328615, coordinate_longitude = 13.485699;
However the error message you're reporting doesn't bear any relation to the code you've posted (as pointed out by alestanis). Your current code shouldn't error, or if it does, it must be a different error message than the one you've mentioned in your question.

Thanks to Dr.Molle I got it working. geocodezip had also the correct answer but I'll use Dr.Molles solution (initialize(); in $(document(ready(function() { ...). Here is the working code.

Related

Google Maps & JavaFX: Display marker on the map after clicking JavaFX button

I have been trying to display a marker on the map when I click on a Button of my JavaFX application. So what happens is when I click on that button, I write the position in a JSON file, this file will be loaded in the html file that contains the map. The problem is that it works perfectly when I open the html page in the browser, but nothing happens in the JavaFX's web view, and I don't know why !
This is the html file:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
/*#map {
height: 100%;
}*/
#map{width:100%;height:100%;margin:auto;}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var marker;
// Multiple Markers
var markers = [];
var pos = {lat: 46.662388, lng: 0.3599617};
var itinerary_markers = [];
function initMap() {
var currentLat, currentLng;//Latitude et longtitude courante
$.ajax({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=My+ADDRESS&key=MY_KEY',
async: false,
dataType: 'json',
success: function (data) {
currentLat = data.results[0].geometry.location.lat;
currentLng = data.results[0].geometry.location.lng;
}
});
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: currentLat, lng: currentLng},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
/*MARQUEUR*/
$.ajax({
async: false,
url: 'test.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.hydrants.length; i++) {
markers.push( data.hydrants[i]);
}
}
});
var posi = new google.maps.LatLng(markers[0].Lat, markers[0].Lng);
marker = new google.maps.Marker({
position: posi,
map: map,
//title: markers[i][0]
title: markers[0].Name
});
}
</script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&language=fr"
async defer></script>
</body>
</html>
When I click the button, I fill the JSON file (which works perfectly) and then I execute this to refresh the webview:
this.webView.getEngine().load(getClass().getResource("/data/index.html").toString());
As I said before, when I open the file on the browser I see the expected result, but I don't know what is the problem with the JavaFX.
If there is a better way to do this please tell me.
EDIT:
I found a solution to the problem by sending directly the data (the GPS coordinates) from JavaFX to Javascript using the executeScript() method, so I don't need a json file as bridge between the two platforms.
So this is an example of how the code looks like:
eng.executeScript("updateMarker(" + lat + ", " + lng + ")");//eng is a WebEngine instance
And here is the Javascript:
/*The initial latitude and longtitude*/
var currentLat = the latitude;
var currentLng = the longtitude;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: currentLat, lng: currentLng},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var posi = new google.maps.LatLng(currentLat, currentLng);
marker = new google.maps.Marker({
position: posi,
map: map,
visible: false
});
}
/*The method that is I call from JavaFX*/
function updateMarker(_lat, _lng){
marker.setPosition({lat: _lat, lng: _lng});
map.setCenter(new google.maps.LatLng(_lat, _lng));
marker.setVisible(true);
}
Thank you for your comments and answers, and a special shootout to reddit.
If I had to guess - one of two things is happening:
Either A) your javaFX is not supporting cross site ajax calls or B) it is not waiting for the asynchronous ajax response/something else is going wrong.
So let's do some testing together. Firstly can we clean this up to nest the ajax calls? Then can you add in some console.log statements to find out what each is sending back? If you miss some output we know where it's going wrong and that'll help us fix things.
Note I've changed success to the 'done' additions because success is a bit out of date, and everything is nested to eliminate the question around whether any blanks are being sent in to the next calls (synchronicity issues):
$.ajax({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=My+ADDRESS&key=MY_KEY',
async: false,
dataType: 'json'
}).done(function(data) {
currentLat = data.results[0].geometry.location.lat;
currentLng = data.results[0].geometry.location.lng;
console.log(currentLat);
console.log(currentLng);
// Multiple Markers
var markers = [];
var pos = {lat: 46.662388, lng: 0.3599617};
var itinerary_markers = [];
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: currentLat, lng: currentLng},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
console.log(map);
/*MARQUEUR*/
$.ajax({
async: false,
url: 'test.json',
data: "",
accepts:'application/json',
dataType: 'json'
}).done(function(data) {
for (var i = 0; i < data.hydrants.length; i++) {
markers.push( data.hydrants[i]);
}
console.log(markers);
var posi = new google.maps.LatLng(markers[0].Lat, markers[0].Lng);
console.log(posi);
var marker = new google.maps.Marker({
position: posi,
map: map,
//title: markers[i][0]
title: markers[0].Name
});
console.log(marker);
}).fail(function(jqXHR, testStatus){
console.log(textStatus);
});
}).fail(function(jqXHR, testStatus){
console.log(textStatus);
});
Here is a link on getting the console.log output in to System.out in Java if this is an issue:
JavaFX 8 WebEngine: How to get console.log() from javascript to System.out in java?
...Also hello from reddit.
In the line:
this.webView.getEngine().load(getClass().getResource("/data/index.html").toString());
I would try double-checking the path to the file is correct. Reading other answers on StackOverflow, it looks like this is supposed to be relative to the package root and either with or without the leading '/'. i.e. getResource("data/index.html"). But, then again, maybe you would already be seeing errors related to getResource()...
My next go to, for debugging purposes, would be to comment out the part where you write the JSON and just manually write some good JSON and just try to get it to show up in the webView. The fewer moving parts, the better. If you can get it to work with your pre-written JSON then you can assume it is some problem with the JSON you are writing with Java and then it being loaded to the HTML.
Edit: I dug a bit deeper. This could be totally wrong again but maybe you can try manually calling the initMap() function from Java that your web browser normally calls onload. How to call a JavaScript function from a JavaFX WebView on Button click? has some more details. Try this.webView.getEngine().executeScript("initMap()"); after you edit the JSON with your button.
Edit 2 As an aside, too, it might make sense to split initMap into an initMap and updateMap function for making the map to begin with and then setting the markers on the map. Though this is hardly breaking anything.
If your mouse-wheel is used to zoom the map out or in and the marker appears, then you are experiencing the same issue that I did.
Try manually zooming the mapview to restore the markers. I also had to employ this technique when displaying a route from the Directions Service, otherwise the waypoint markers were not displaying correctly.
This is the code in my Javafx controller class to do so:
KeyFrame kf1 = new KeyFrame(Duration.seconds(0.75), e -> map.setZoom(map.getZoom() - 1));
KeyFrame kf2 = new KeyFrame(Duration.seconds(1.5), e -> map.setZoom(map.getZoom() + 1));
Timeline timeline = new Timeline(kf1, kf2);
Platform.runLater(timeline::play);
This was using GMapsFX, which is just a thin Java wrapper around javascript engine calls on a JavaFX WebView. Hopefully it helps.

One of my variables is being set in initMap, but when I call another function inside the script that same variable is suddenly undefined

I original had this question posted, but wouldn't let me edit post nor resign in. In this I hope to have refocus and make it clear what I am asking for.
I define my map in the callback function of Google Maps Api. initMap is definitely being called first. Once it is I manually trigger the addVehicleMarker method.
This is how it is being called in HTML side:
// index.html
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<script defer src="../src/map-manager.js"></script>
This is what I am doing in initMap below:
// map-manager.initMap
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: home_latlng,
streetViewControl: false
});
My issue
I want to import my map-manager.js class elsewhere. Mainly for the addVehicleMarker method. When I do the following...
var MapManager = require('../src/map-manager');
MapManager.addVehicleMarker(v);
map in map-manager.js is now undefined.
When I do...
addVehicleMarker(v);
map in map-manager.js has the map which I defined in initMap. Without my even having to import the file.
Question
How can I achieve the same thing in addVehicleMarker(v); while allowing my to import it properly and called it as MapManager.addVehicleMarker(v);, while retaining map?
This is the rest of the source:
// map-manager.js
var VehicleManager = require('../src/vehicle-manager');
var WampTasks = require('../src/wamp-tasks');
var map;
var vehicleMarkers = [];
function initMap() {
const home_latlng = {
lat: 33.816714399999995,
lng: -117.90523610000001
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: home_latlng,
streetViewControl: false
});
}
// http://blog.mridey.com/2010/03/using-markerimage-in-maps-javascript.html
function addVehicleMarker(vehicle) {
console.log(map);
var icon = new google.maps.MarkerImage(
vehicle.iconLocation,
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(32, 32)
);
var marker = new google.maps.Marker({
position: vehicle.currentLatLng,
icon: icon,
map: map
});
console.log(marker);
// marker.setTitle(String(vehicle.displayName));
vehicleMarkers.push(marker);
console.log(vehicleMarkers);
}
module.exports = {};
module.exports["addVehicleMarker"] = addVehicleMarker;
Seems a var scope issue. Declare var map at window level (and remove if presente other nested var maps; delacration
<script>
var map;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: home_latlng,
streetViewControl: false
});
....
</script>

google map api, link to URL

Sorry for asking a simple question I surely can find easily by reading the API docs, but a client just asked me this in general, and I would like to answer him asap.
Situation:
I have a custom map created, with public (or restricted to user) access, where are different markers.
Q1)Is it possible to create markers via the API using e.g. custom data from our database?
Q2)Ist it possible to add a URL to a marker, so that a user clicks on it and gets to a specific site, where he can e.g. vote for this location? (just as an example)
Thanks in advance to everyone, and once more sorry not to look closer by myself
Cheers,
Phil
Following Function Will Create Marker
<script type="text/javascript">
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
TestMarker();
}
// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Testing the addMarker function
function TestMarker() {
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);
}
For Clicking and URL Use Following Technique
var points = [
['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];
var marker = new google.maps.Marker({
...
zIndex: place[3],
url: place[4]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});

Google Maps Failing to render

Note: I thought it would be better to make a new question on this.
So I recently asked a question about why Google maps is not rendering properly. Now the answer would seem straight forward and simple, accept my code looks like this:
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.trigger(map, "resize");
}
google.maps.event.addDomListener(window, 'load', initialize);
The issue is the map is still broken:
This map is stored in a <div id="Map"></div> which has a height of 350. This Div that holds the map is part of Jquery-UI Tabs, so it also has jquery skinning attached to it which may affect things like size and so on.
With that said the map should just work.
If I open the console and throw in: google.maps.event.trigger(map, "resize"); the maps then works as expected.
I also had a Google Map (v3) embedded within a jQuery UI Tabs, and had to work around the issue with this fix:
var initialized = false;
$('.tabs').find('.ui-tabs-nav li').each(function() {
if($(this).find('a').text() === 'Location') {
if($(this).hasClass('ui-state-active')) {
initialize();
initialized = true;
} else {
$(this).click(function() {
if(!initialized) {
initialize();
initialized = true;
}
});
}
}
});
Note that initialize() should run your starting map code. There are lots of ways to slice-and-dice the initialization, but the point is that we don't do it until the tab we're looking for ("Location", in this case) is active.

How to add Markers on Google maps v3 API asynchronously?

I've been following the official documentation on how to add markers on the map so far
Nevertheless, I can see only one marker at a time max. If I try to add another one, then it doesn't work (I can't even see the first one).
My process is the following:
I initialize gmaps api:
jQuery(window).ready(function(){
//If we click on Find me Lakes
jQuery("#btnInit").click(initiate_geolocation);
});
function initiate_geolocation() {
if (navigator.geolocation)
{
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBbfJJVh0jL1X9b7XFDcPuV7nHD1HlfsKs&sensor=true&callback=initialize";
document.body.appendChild(script);
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
}
else
{
yqlgeo.get('visitor', normalize_yql_response);
}
}
Then, I display it on the appropriate div. But when it comes to make the AJAX call, in order to get my locations of the different markers I'd like to display, It just doesn't work properly. Here is the code with a simple map displayed (since that's the only thing working for me so far).
function handle_geolocation_query(position){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
alert('Lat: ' + position.coords.latitude + ' ' +
'Lon: ' + position.coords.longitude);
$('#map-canvas').slideToggle('slow', function(){
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
$.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(results) {
// InitializeGoogleMaps(results);
if(results)
var data = results.map(function (lake) {
//Check if the lake has any open swims, if not, the button will not be clickable and an alert will pop up
if (lake.available>0)
clickable=true;
else
clickable=false;
return {
name: lake.name,
fishs: lake.fisheryType,
swims: lake.swims,
dist: lake.distance,
lat: lake.latitude,
long: lake.longitude,
id: lake.id,
avail: lake.available,
clickable: clickable,
route: Routing.generate('lake_display', { id: lake.id, lat: position.coords.latitude, lng: position.coords.longitude})
}
});
var template = Handlebars.compile( $('#template').html() );
$('#list').append( template(data) );
} );
};
So I'd like to add markers after the AJAX call. I've set up a function that I should call in the when()
function InitializeGoogleMaps(results) {
};
to display the markers in a foreach loop but nope, can't make it work. It looks like this :
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
marker = new google.maps.Marker({
position: location,
map: map
});
Any help would be great !
Thanks
The main issue is that the map variable is declared only in the scope of the anonymous callback on slideToggle. First of all declare at the top-level function scope.
function handle_geolocation_query(position){
var map,
mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
...
Then change the slideToggle callback to initialise the variable instead of redeclaring:
$('#map-canvas').slideToggle('slow', function(){
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
Then you should pass map as a second parameter to your InitializeGoogleMaps function and call it using InitializeGoogleMaps(results, map). See where this gets you and hit me back with any questions.

Categories

Resources