I'm getting (NaN, NaN) when I trying to fetch the latitude and longitude information from an GET in JavaScript. Here's my code:
var GET = {};
var params = location.search.substr(1).split("&");
for (var i=0; i < params.length; i++) {
var par = params[i].split('=');
GET[par[0]] = par[1];
}
function initialize() {
var latitude_longitude = new google.maps.LatLng(GET['coordinates']);
// The basic code to call Google Maps JavaScript API v3 ...
}
Do I have to put the latitude and longitude in clear text (for example ... new google.maps.LatLng(59.328614,13.485847))?
Thanks in advance.
LatLng() takes two arguments, so you will need to split the coordinates:
function initialize() {
var csplit = GET['coordinates'].split(',');
var latitude_longitude = new google.maps.LatLng(csplit[0], csplit[1]);
// The basic code to call Google Maps JavaScript API v3 ...
}
Can you elaborate, what's stored in coordinates?
You might have to use split(','), then write new google.maps.LatLng(parseFloat(value[0]),parseFloat(value[1]))
Related
I am attempting to piece together an example from ml5 on image style transfer (https://ml5js.org/docs/style-transfer-image-example) with p5.js examples parsing a JSON of image URLs, and adding them to an array to display as images. I am hitting a dead end as I do not think I fully understand the ways that p5 stores images in an array, nor do I fully understand the difference between createImg() createImage() or loadImage() (which one to use!!)
The goal is to use Bing image API to return a list of URLS from a search (this part is working fine) and run those images through a pretrained model (this part is working fine when just used on a local image). It is the bringing the two together that I am unable to figure out. Any suggestions or advice (is this even possible??!) greatly appreciated.
I have already tried loading images into an array and iterating through the array in the draw() function. The problem happens when I need to address an image in order to actually apply the style transfer model. It seems like my array is empty when I attempt to refer to it anywhere except draw(). I am sure I am thinking about this incorrectly.
var imageData;
let imgArray = [];
var w = (window.innerWidth)/3;
var h = (window.innerHeight)/4;
var index = 0;
var xPos = 0;
var yPos = 0;
var indexMax = 3;
let style;
let resultImg;
function preload() {
loadData();
}
function loadData(){
var url = api + search + subscriptionKey;
loadJSON(url, gotData);
}
function gotData(data) {
imageData = data;
for (var i=0; i < indexMax; i++){
_url = imageData.value[i].contentUrl;
imgArray.push(loadImage(_url));
}
function displayImages(){
if (index < 3){
index++;
} else {
index = 0;
};
function setup() {
createCanvas(1200, 800).parent('canvasContainer');
var button = select('#display');
button.mousePressed(displayImages);
var transferBtn = select('#transferBtn');
transferBtn.mousePressed(transferImages);
//create style method
style = ml5.styleTransfer('/model', modelLoaded);
}
function draw() {
image(imgArray[index], xPos, yPos, w, h);
}
//ml5 stuff
function modelLoaded() {
if (style.ready){
select('#status').html('Model Loaded');
//style.transfer(gotResult);
}
}
function transferImages(){
select('#status').html('applying style transfer');
style.transfer(tempImg, function(err, result){
createImg(result.src);
});
select('#status').html('done');
}
I am attempting to (unsuccessfully) create a "tempImg" from imgArray[0] to try to figure out where this createImage needs to go, but have not gotten this to work. I have CORS enabled, so I didnt think this was the problem, but am getting the following error. Please help me understand how to think about this differently.
You should use loadImage instead of createImg.
style.transfer(tempImg, function(err, result){
p5CompatibleImage = loadImage(result.src);
});
All my markers are placed in the array "markersArray[]". I want to parse through them and retrieve their current individual latitude and longitude so I can add them to a string I then pass to PHP. Here are all the ways I've tried with no luck (getting latitude only for testing purposes).
function test() {
alert("markersArray.length " + markersArray.length)
for( var i = 0, n = markersArray.length; i < n; ++i ) {
var markerLat = parseFloat(markersArray[i].getAttribute("lng"))
//var markerLat = map.markersArray[i].getPoint().lat();
//var markerLat = map.markersArray[i].getPoint().lat();
//var markerLat = map.markersArray[i].latLng.lat().toFixed(3);
//var markerLat = map.markersArray[i].position.lat();
alert("markerLat " + markerLat)
}
}
I have no problem getting other attributes of the markers, I don't understand why this should be so difficult. :(
Why guess? The documentation says google.maps.Marker.getPosition() (assuming your markersArray contains google.maps.Marker objects, you don't provide the code that initializes it).
I'm trying to change the radius category/type filter for a checkbox, so I changed the var type to an array.
ORIGINAL WORKING:
var type;
for (var i = 0; i < document.controls.type.length; i++){
if (document.controls.type[i].checked){
type = document.controls.type[i].value;
}
}
startBox.setBounds(map.getBounds());
var search = {
// keyword: 'comocomo', // not needed with the autocomplete / startBox
bounds: map.getBounds()
};
if (type != 'establishment'){
search.types = [ type ];
}
places.search(search, function(placesArr, status){
THE ONE WITH THE ARRAY NOT WORKING: edited:
var type=[];
for (var i = 0; i < document.controls.type.length; i++){
if (document.controls.type[i].checked){
type.push(document.controls.type[i].value)
}
}
startBox.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
var quotedAndCommaSeparated = "'" + type.join("','") + "'";
alert(quotedAndCommaSeparated); // 'establishment','restaurant','lodging'
search.types = [ quotedAndCommaSeparated ];
I made many tests, and I don't see what I'm doing wrong. the map doesn't even show.
What's this meant to be, doesn't look like valid Javascript to me:
var type[];
Should be
var type = [];
Fix the javascript errors in your code otherwise the map won't show up.
Update:
What you have in quotedAndCommaSeparated is a string like "'a','b','c'" that looks a bit like the contents of an array: ['a','b','c']. But it's not an array, it's just a single string. If you check the length of your search.type array, I'm guessing it equals 1.
What you can do is split your string on the comma to turn it into an array:
search.types = quotedAndCommaSeparated.split(",");
I have a some UI elements on the right of my map (sometimes), and I'd like to offset my panTo() calls (sometimes).
So I figured:
get the original latlng
convert it to screen pixels
add an offset
convert it back to latlng.
But I must misunderstand what Google Maps API refers to as the "Point Plane":
http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection
Here is my code that seems to offset by lat-long:
function getCentreOffset( alatlng ) {
var PIXEL_OFFSET= 100;
var aPoint = me.gmap.getProjection().fromLatLngToPoint(alatlng);
aPoint.x=aPoint.x + OFFSET;
return me.gmap.getProjection().fromPointToLatLng(aPoint);
}
Here's a simpler version of Ashley's solution:
google.maps.Map.prototype.panToWithOffset = function(latlng, offsetX, offsetY) {
var map = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function() {
var proj = this.getProjection();
var aPoint = proj.fromLatLngToContainerPixel(latlng);
aPoint.x = aPoint.x+offsetX;
aPoint.y = aPoint.y+offsetY;
map.panTo(proj.fromContainerPixelToLatLng(aPoint));
};
ov.draw = function() {};
ov.setMap(this);
};
You can then use it like this:
var latlng = new google.maps.LatLng(-34.397, 150.644);
var map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng
});
setTimeout(function() { map.panToWithOffset(latlng, 0, 150); }, 1000);
Here is a working example.
Let me explain in detail. This extends the Map object itself. So you can use it just like panTo() with extra parameters for offsets. This uses the fromLatLngToContainerPixel() and fromContainerPixelToLatLng() methods of the MapCanvasProjecton class. This object has no contructor and has to be gotten from the getProjection() method of the OverlayView class; the OverlayView class is used for the creation of custom overlays by implementing its interface, but here we just use it directly. Because getProjection() is only available after onAdd() has been called. The draw() method is called after onAdd() and is defined for our instance of OverlayView to be a function that does nothing. Not doing so will otherwise cause an error.
Answer by Dean looks a lot cleaner as said in some comments, but was looking a little complicated to me. This single line solution is looking more elegant to me.
var map = $('#map_canvas').gmap3("get")
map.panBy(-500,-500); // (x,y)
Set center of map first. Then panyBy will shift the center in (x,y) direction. The more negative x, map will shift right. The more negative y, map will shift down.
Ok I found the answer here: How to call fromLatLngToDivPixel in Google Maps API V3?
First create function/prototpe to access the map's projection (difficult in V3)
//declare function/prototpe
function CanvasProjectionOverlay() {}
//define..
CanvasProjectionOverlay.prototype = new google.maps.OverlayView();
CanvasProjectionOverlay.prototype.constructor = CanvasProjectionOverlay;
CanvasProjectionOverlay.prototype.onAdd = function(){};
CanvasProjectionOverlay.prototype.draw = function(){};
CanvasProjectionOverlay.prototype.onRemove = function(){};
var gmap;
var canvasProjectionOverlay;
var PIXEL_OFFSET= 100;
function showUluru(isOffset=false){
//create map
var gmap = new google.maps.Map($('#map_canvas', {});
//create projection
canvasProjectionOverlay = new CanvasProjectionOverlay();
canvasProjectionOverlay.setMap(gmap);
var uluruRock = new google.maps.LatLng(-25.335448,135.745076);
if (isOffset)
uluruRock = getCentreOffset(uluruRock);
gmap.panTo( uluruRock )
}
//Use this function on LatLng you want to PanTo();
function getCentreOffset( alatlng ) {
var proj = canvasProjectionOverlay.getProjection();
var aPoint = proj.fromLatLngToContainerPixel(alatlng);
aPoint.x=aPoint.x+PIXEL_OFFSET;
return proj.fromContainerPixelToLatLng(aPoint);
}
Hi I'm wondering if anybody could help me with a problem I'm trying to solve with Flex & google maps.
I have a map that is populated by markers. Each marker has an event listener. And what I am hoping to achieve is that when each marker is clicked that a datagrid is populated with the data associated to that marker. However at the moment I can only populate the data grid with the LatLng object. I need to find a way to access the other data associated with that Marker.
Here is my event listener:
private function createMarker(latlng:LatLng, int:Number, tip:String, desc:String):Marker
{
var m:Marker = new Marker (latlng, new MarkerOptions ({hasShadow: true, tooltip: "" +tip}));
m.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void
{details.addItem(event.latLng.toString());});
return m;
}
I was thinking it might be along the lines of getitem where LatLng = event.latLng but I'm really new to flex so I can't figure it out at all.
Any ideas that might put me on the right track would be really appreciated.
L
Try this:
private var markerArray:Array = [];
private var markerDescriptsArray:Array = [];
private function createMarker(latlng:LatLng, int:Number, tip:String, desc:String):Marker
{
var m:Marker = new Marker (latlng, new MarkerOptions ({hasShadow: true, tooltip: "" +tip}));
m.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void
{
var _mIndex:uint;
for (var i:uint = 0; i < markerArray.length; i++)
{
if(markerArray[i] == Marker(e.currentTarget)) _mIndex = i;
}
details.addItem(markerDescriptsArray[_mIndex]);
});
markerArray.push(m);
markerDescriptsArray.push(desc);
return m;
}