How to pan on google maps? - javascript

I'm working on simple App which provide for our clients our branches location, I use now a snapshot of the map, but I want to show the location on real map (Pan) not just an image.
I use Intel XDK platform (HTML/Javascribt)
This is the code I use:
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var output = document.getElementById("mapp");
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=400x400&sensor=false";
output.appendChild(img);
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, onError);

I found the answer, just by changing success function to:
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var bangalore = { lat: 12.97, lng: 77.59 };
var map = new google.maps.Map(document.getElementById('mapp'), {
zoom: 14,
center: bangalore
});
var beachMarker = new google.maps.Marker({
position: bangalore,
map: map,
});

Related

Script not working when trying to getJSON from URL that I put lat & long data into

As you can see here, my app doesn't work when I try to use the variables "latitude" and "longitude" (those variables should get the user's current latitude and longitude) in the URL that I am getting JSON from.
Below is my code
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude
var longitude = position.coords.longitude
})
}
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, function(json){
var temp = json.main.temp
var ftemp = (temp * 1.8) + 32
var celsius = true
var condition = json.weather[0].main
var video;
switch (condition)
{
case "Clouds":
video = ""
break;
case "Rain":
video = "https://gcs-vimeo.akamaized.net/exp=1523487613~acl=%2A%2F401800757.mp4%2A~hmac=d66772ad9d6530ff1af68ac1dc01fcf17db42cce48ff72eebf97cc2b34ec0dab/vimeo-prod-skyfire-std-us/01/2146/5/135733055/401800757.mp4"
break;
case "Sunny":
video = ""
break;
}
$("#myVideo").html("<source src='" + video + "' type='video/mp4'>")
$("#condition").html(condition)
$("#number").html(Math.round(temp) + "°C")
$("#button").on("click", function(event){
event.preventDefault()
celsius = !celsius;
if (celsius)
{
$("#number").html(Math.round(temp) + "°C")
$("#button").html("(Switch to °F)")
}
else
{
$("#number").html(Math.round(ftemp) + "°F")
$("#button").html("(Switch to °C)")
}
})
})
But before I added the upper "if portion" and before I tried putting the variables into the URL, the app worked just fine, so the issue is somewhere in these few lines below.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude
var longitude = position.coords.longitude
})
}
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, function(json){
Your variables are going out of scope:
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude
var longitude = position.coords.longitude
})
}
You need to declare the variables outside of that inner function:
var latitude, longitude;
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude
longitude = position.coords.longitude
})
}
Oh, and you'll need to wait until you have gotten the coordinates, so you should wrap your getJSON call in a function, and then call it after you have the variables.
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude
longitude = position.coords.longitude
doAjaxRequest();
})

Google Maps is grey after being called a second time

I am looping through some JSON files and using the address from the JSON file for the google maps. I know the address is working properly because I set an alert to show the variable and it's showing what I expect. The call for the map is inside a click function. on one virtual page I have a list of customers and when the user clicks that customer, it redirects to another virtual page to display that customers information, with a map showing their address. When I do this for the first time , it works. If I click back, then select a different customer the map is just grey. Any idea why this is happening?
Here is my click function..
function cHandle(num) {
$("#custSpan" + i).on("click", function () {
window.location.href = "#CustInv";
custName = customer.Customer[num].compName;
$("#CustInvHead").html(custName);
$("#invoiceh2").html(custName + "'s Invoices");
$("#custInfo").empty();
$("#invoice").empty();
$("#map-canvas").empty();
var inc = customer.Customer[num].compId;
$("#custInfo").append("Customer ID: " + customer.Customer[num].compId + "<br /><br />"
+"Customer Name: " + custName + "<br /><br />"
+"Customer Address: " + customer.Customer[num].compAddress + "<br /><br />"
+"Customer Contact: " + customer.Customer[num].compContact + "<br /><br />"
+"Customer Phone: " + customer.Customer[num].compPhone + "<br/ ><br />"
+ "Customer Email: " + customer.Customer[num].compEmail + ""
);
address = customer.Customer[num].compAddress;
//alert(address);
codeAddress();
})
}
cHandle(i);
And here is my maps stuff..
function success(pos) {
lat = pos.coords.latitude;
lng = pos.coords.longitude;
drawMap();
}
function error(err) {
alert("Error " + err.code + " : " + err.message);
}
;
function codeAddress() {
lat = 0;
lng = 0;
//Get the address
//address = "123 Fake St";
if (address == "") {
alert("No Address Entered");
return;
}
//Change address to coordinates to plot on map
else {
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myLatLng = results[0].geometry.location;
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
drawMap();
}
else {
alert("Geocode was not successful for the following reason: " + status);
return;
}
})
}
}
function drawMap() {
mapCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: mapCenter,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Display the address
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//Map Marker
var myLoc = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: mapCenter
});
You call several times the creation of the map as you should call once (Initialize) map and call several times the function of creating the marker.
split the code in drawMap in two
first declare the var map at top (window) level (outside the functions)
and initialize your map
var map
function initialize() {
mapCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: mapCenter,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Display the address
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addDomListener(window, 'load', initialize);
</script>
second in the codeAddress() function call only the create marker function
function createMarker() {
var myLoc = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: mapCenter
});
}

How to save a variable value outside of a function in javascript

I am newbie to JavaScript, I was trying to make a simple GoogleMaps which is centered in my current position and I am finding problems saving my latitude and longitude to center the map.
Here is my code which i have adopted:
function initialize() {
var latitudeCenter;
var longitudeCenter;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position){
console.log(position.coords.latitude, position.coords.longitude);
latitudeCenter = position.coords.latitude;
longitudeCenter = position.coords.longitude;
}
function onError(error){
alert('Error en GPS: ' + error);
}
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}
In the first console log I can read my current position and latitude, so that method works fine, but when I try to save it in centerLatitude and centerLongitude it does not work, it displays undefined.
Thanks for the help
So, the functions onSuccess and onError are asynchronous, so you won't get back an answer straight away. So therefore you put your actual map initialisation code inside that onSuccess
function initialize() {
var latitudeCenter;
var longitudeCenter;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position){
console.log(position.coords.latitude, position.coords.longitude);
latitudeCenter = position.coords.latitude;
longitudeCenter = position.coords.longitude;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
}
function onError(error){
alert('Error en GPS: ' + error);
}
console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}

Google Maps search for duplicate lat and lng

For each location I'm adding a png icon.
In my database I have many entries with the same lat and lng. Is there a way I can find the entries with the duplicate lat and lng and apply a different icon?
function displayStores(result){
if (result.length > 0){
for (i=0;i<result.length;i++){
//Append Store Address on Sidebar
var html = getEmbedHTML(i+1,result[i].name,result[i].address,result[i].distance);
$("#divStores").append(html);
//place a marker
var image = 'images/number_' + parseInt(i+1) + '.png';
var latlng = new google.maps.LatLng(result[i].lat,result[i].lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var msg = 'Location : ' + result[i].name + '<br/> ';
msg = msg + 'Address : ' + result[i].address + '<br/> ';
attachMessage(marker, msg);
}
} else {
$("#divStores").html('No Stores Found');
}
}
You can sort the points and compute the difference. When it's greater then 0 then you can change the icon.

InfoWindow & GeoCoder

I have an issue with getting longitude and latitude values geocoded and then display the relevant address in an info window. I have tried multiple ways without success, however I must admit that I am not so familiar with javascript. I am continuously getting back as value : "undefined".
Here is a snippet of my code showing the main components:
var position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var geocoder = new google.maps.Geocoder();
var address;
if (geocoder) {
geocoder.geocode({ 'latLng': position }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
address = (results[0].formatted_address);
} else {
address = (position.coords.latitude + ', ' + position.coords.longitude);
}
});
}
var info =
('<span class="txt_bld">Location:</span> ' + address + '<br />' +
'<span class="txt_bld">Accuracy:</span> ' + position.coords.accuracy + '<br />' +
'<span class="txt_bld">Time:</span> ' + position.timestamp);
Can anyone tell me how I can translate the lat/lng in position to an address in order to show them in my infowindow?
EDIT
Updated Code:
var position = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var address;
if (geocoder) {
geocoder.geocode({ 'latLng': position }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
address == (results[0].formatted_address);
} else {
address == (position.coords.latitude + ', ' + position.coords.longitude);
}
var info =
('<span class="txt_bld">Location:</span> ' + address + '<br />' +
'<span class="txt_bld">Accuracy:</span> ' + position.coords.accuracy + '<br />' +
'<span class="txt_bld">Time:</span> ' + position.timestamp);
if(!infowindow){
infowindow = new google.maps.InfoWindow({
content: info
});
}else{
infowindow.setContent(info);
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
setTimeout(function () {
infowindow.close();
}, 5000);
});
});
}
if(!marker){
marker = new google.maps.Marker({
position: position,
map: this.map,
icon: markericon,
draggable:false
});
}else{
marker.setPosition(point);
}
The geocoder is asynchronous. You need to use the data it returns in the callback function. Something like this (not tested):
var position = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var address;
if (geocoder) {
geocoder.geocode({ 'latLng': position }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
address = (results[0].formatted_address);
} else {
address = (position.coords.latitude + ', ' + position.coords.longitude);
}
var info =
('<span class="txt_bld">Location:</span> ' + address
+ '<br />' +
'<span class="txt_bld">Accuracy:</span> ' + position.coords.accuracy
+ '<br />' +
'<span class="txt_bld">Time:</span> ' + position.timestamp);
infowindow.setContent(info);
infowindow.setPosition(position);
infowindow.open(map);
});
}
Working example
We are using geocoder to get Lat long by address, as we don't have Lat long so we need to find Lat long via geocoder. In case if we have Lat long coordinates then we can use direct
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});

Categories