Replace long/lat on Google maps via AJAX - javascript

I have this map script from Google Maps implemented on my site. What I'd like to do is I'd like to replace the latitude and longitude numbers (lat & lng) with numbers I've fetched from an API via AJAX.
The variables containing the longitude numbers and latitude numbers are returned like: data.mondayLat & data.mondayLong via the successfunction of AJAX. I've tried just replacing the default map setting 00.0000000 with data.mondayLat, but that isn't working. How do I make those variables continuously replace the default numbers in the map function, and make the map update each time I fetch data via AJAX?
<script>
function initMap() {
/* The following variable data I want to replace with the AJAX responde numbers */
var myLatLng = {lat: 00.0000000, lng: 00.0000000};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Today we are here'
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<div id="googleMap" style="width:500px;height:380px;float:lefT;margin-left:20px;border:3px solid;"></div>

Your AJAX request is asynchronous. Call the initMap routine in the AJAX success function once you have the results (data.mondayLat and data.mondayLong exist).

Related

Changing javascript in google maps doesn't update it?

I am trying to make an AJAX map Google map, where the place markers update but not the map.
I have an ajax setup with a settimeout function, which returns new javascript. When the new javascript is loaded into my HTML, the changes do not reflect on my google map.
When I go into the firefox inspector and try and manipulate the javascript, (to try and change marker GPS coordinates), nothing happens to the map, and the points are still the same. Why does that not affect the map?
I have looked at several links to try and help me, but none of them explain the logic behind the javascript.
My PHP script returns javascript in plain text. But when these get
added to the HTML, The google map does not change and looks like it
needs to be re initialized before it recognizes new javascript?
Can someone explain how I should update the javascript, so the map re-centers on the newest marker and places the newest marker without refreshing the page / re initializing the map?
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -20.530637, lng: 46.450046}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
new google.maps.LatLng("-21.530637,46.450046),
new google.maps.LatLng("-22.530637,46.450046),
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'content.php',
type:'POST',
success:function(results) {
locations=results;
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,5000);
</script>
My "content.php" file. returns more google maps LatLng markers in plain text.
so PHP output is:
new google.maps.LatLng("-23.530637,46.450046"),
new google.maps.LatLng("-24.530637,46.450046"),
new google.maps.LatLng("-25.530637,46.450046"),
new google.maps.LatLng("-26.530637,46.450046")
I would like to summary the behavior of your ajax map:
Initialize map (probably with a set of predefined locations)
Repeatedly call content.php to retrieve new update of markers
Draw new markers to your map
The problem is that your code that handles ajax result doesn't do any map manipulation. In fact, it has to update the variable locations with new location set. Then create new markers with updated list of locations, then call MarkerCluster to apply them.
I created a fiddle to demonstrate it: https://jsfiddle.net/anhhnt/paffzadz/1/
What I did is extract the marker creating part from initMap, so that it can be called multiple times after locations is updated.
function updateMarker () {
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
};
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
updateMarker(map);
};
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124}
]
function refresh_div() {
jQuery.ajax({
url:'/echo/json/',
type:'POST',
data: {
json: JSON.stringify([
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
])
},
success:function(results) {
locations.concat(results);
updateMarker();
}
});
}
t = setInterval(refresh_div,5000);
Hope it helps.
Perhaps you have simple syntax error in your code - missing closing double quote:
new google.maps.LatLng("-23.530637,46.450046"),
...
..or better - remove first double quote:
new google.maps.LatLng(-23.530637,46.450046),
...

Google maps API loads for a second then says check js console but no warnings or errors, any ideas

I'm using an API in a website for the first time, the google map pops up with the marker on my location that I have set but immediately goes gray and says check the console, in which there are no errors or warnings.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer>
</script>
<script>
function initMap() {
var albany = {lat: 42.676762, lng: -73.821991};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: albany
});
var marker = new google.maps.Marker({
position: albany,
map: map
});
}
</script>
You need to include a valid key when you load the API.
The console should contain text to that effect and the URL that needs to be authorized.

Panoramas in Google Maps not showing

We're trying to implement panoramas to display in Google Maps in the same way as it's showing
This is an example from our website:
For some reason, on our map it does not show possible panorama locations (inside and outside). How can we get them to show there?
Our code is currently this:
<script>
var latitude = <?= $hotel->latitude ?>;
var longitude = <?= $hotel->longitude ?>;
function initialize() {
var fenway = { lat: latitude, lng: longitude };
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10
},
fullScreenControl: true
};
var panorama = new google.maps.StreetViewPanorama( document.getElementById('pano'), panoramaOptions );
map.setStreetView(panorama);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
From the Street View Service documentation, Street View images are supported through use of the StreetViewPanorama object, which provides an API interface to a Street View "viewer." Each map contains a default Street View panorama, which you can retrieve by calling the map's getStreetView() method. When you add a Street View control to the map by setting its streetViewControl option to true.
The StreetViewPanorama constructor also allows you to set the Street View location and point of view using the StreetViewOptions parameter. You may call setPosition() and setPov() on the object after construction to change its location and POV.
Just take NOTE that not all locations has available streetview
image, unless you created a custom one. Here is the link of the list
of currently supported cities for Street View.
For more information, read all the guides that you can find in this documentation and the samples that you can find here.

Google maps js api. Many maps on page

I have accordion (twitter-bootstrap), and on each I have a map.
Accordion blocks generates in foreach. Maps generates as partial view, that takes model with latitude and longitude and block id.
It calls in foreach:
#if (item.Latitude != null)
{
<p>Map:</p>
<div class="map-margin">
#{Html.RenderAction("Map", "Default", new {model = item});}
</div>
}
And action returns this partial view:
#model MPS.Administration.Models.ReportModel
<div id="map-canvas-#Model.Id.ToString()" style="width: 470px; height: 270px;"></div>
<script type="text/javascript">
$('#map-canvas-#Model.Id').ready(function() {
initialize();
});
function initialize() {
var lat = #Model.Latitude;
var lng = #Model.Longitude;
var latlng = new google.maps.LatLng(#Model.Latitude, #Model.Longitude);
debugger;
var mapOptions = {
center: latlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var name = 'map-canvas-' + #Model.Id.ToString();
var map = new google.maps.Map(document.getElementById(name),mapOptions);
debugger;
// create a marker
var image = '../Content/Images/map_icon.png';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
}
</script>
On layout I included script for js api.
Now I have 4 blocks, but only the last have map block (and it have only google logo and gray background without the map :( ). In debugger I see that lat and lng is same all 4 times. I think the problem is how I call initialize() map. Please help me to solve this issue.
The map si show only in the visible div. For the other you shuuld see only a grey background and in some case a small portion of the map in the upper left corner.
For see the map in every block you should use map.resize() or better use a genaration function for each time you show a new map. Initialize tipcally is call only when the windows is created and this this case the maps not visible fails

how to load vb.net variable to javascript

I'm trying to add google maps to my website, but instead of fixing a latitude and longitude for the location, I would like to be able to load the values from database. How do I get a variable from vb.net and pass it to javascript? I've tried:
<% Response.Write("<script>
function initialize() {
var myLatlng = new google.maps.LatLng(1.123456, 1.123456);
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'KH Automotive Location'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>")%>
and
new google.maps.LatLng(<%=latitude%>, <%=longitude%>);
Please help. Thanks
Sometimes, when I need to make absolutely sure (like with translated/localized strings) that the content comes across, I'll write it out to a hidden DIV somewhere on the page (or a hidden INPUT).
<div style='display:none' id='my_data'>stuffstuffstuff</div>
Then I just read the contents of the DIV (or INPUT, whatever I used). Slap a "runat=server" in it, and be able to write to it from your code-behind.
Should be able to write it in:
<% Response.Write("..
..
var myLatlng = new google.maps.LatLng(" & latitude & ", " & longitude & ");
..
")%>

Categories

Resources