Google maps LatLngBounds doesn't work sometimes with a javascript object - javascript

I have a problem with my map. I'm using the google maps funtion LatLngBounds() in order to calculate the center between two given points.
I'm able to get the location and I consoled.log the value (even if, for some reason the values are empty, I'm still able to print them to the map) so I'm able to place my markers on the map, but for some reason, when I add the function for the bound, I break the map, I get an error and I'm only able to see a marker (one marker.
Here's my code:
var locs;
function initMap() {
var locations_two = [
['<div class=""><p>Vancouver</p></div>', 49.27597, -123.1185, 1],
['<div class=""><p>Ottawa</p></div>', 45.3683, -75.70258]
];
locs = new google.maps.Map(document.getElementById('locs'), {
center: {lat: 49.276873, lng: -123.118948},
zoom: 4
});
var image = $myimage;
var infowindow = new google.maps.InfoWindow();
var marker_two, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations_two.length; i++) {
var mybond = locations_two[i];
var myLatLng = new google.maps.LatLng(mybond[1], mybond[2]);
marker_two = new google.maps.Marker({
position: myLatLng,
map: locs,
icon: image
});
bounds.extend(myLatLng);
google.maps.event.addListener(marker_two, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations_two[i][0]);
infowindow.open(map, marker);
}
})(marker_two, i));
map.fitBounds(bounds);
}
}
As I said, I declared the variable var bounds = new google.maps.LatLngBounds(); before the loop and then I use the two other google map function in order to call the map.fitBounds(bounds); at the very end, to center my map but I get this error:
Uncaught (in promise) TypeError: Cannot read property 'fitBounds' of undefined
Which doesn't make sense for me because the bounds variable is actually defined? Any thoughts?

With the posted code I get a javascript error (in Chrome):
Uncaught (in promise) ReferenceError: map is not defined
Your google.maps.Map object is named locs, not map. This line:
map.fitBounds(bounds);
should be:
locs.fitBounds(bounds);
proof of concept fiddle
code snippet:
var locs;
function initMap() {
var locations_two = [
['<div class=""><p>Vancouver</p></div>', 49.27597, -123.1185, 1],
['<div class=""><p>Ottawa</p></div>', 45.3683, -75.70258]
];
locs = new google.maps.Map(document.getElementById('locs'), {
center: {
lat: 49.276873,
lng: -123.118948
},
zoom: 4
});
var infowindow = new google.maps.InfoWindow();
var marker_two, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations_two.length; i++) {
var mybond = locations_two[i];
var myLatLng = new google.maps.LatLng(mybond[1], mybond[2]);
marker_two = new google.maps.Marker({
position: myLatLng,
map: locs,
});
bounds.extend(myLatLng);
google.maps.event.addListener(marker_two, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations_two[i][0]);
infowindow.open(map, marker);
}
})(marker_two, i));
locs.fitBounds(bounds);
}
}
html,
body,
#locs {
height: 100%;
margin: 0;
padding: 0;
}
<div id="locs"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

Related

HTML5 geolocation info window not working

I need to create info-window out of this code, I'm lacking of application logic and totally new to programming i use this open-source code
This code add users to the map along with their marker
function loadMarkers(data) {
for(key in data) {
var user = data[key];
xmartlabschat.addUser(user);
markers[key] = getMarker(user.lat, user.lng, user.name);
}
}
I tried to use the basic code for info-window
var infoWindow = new google.maps.InfoWindow(user.name);
markers[key].addListener('click', function(){
infoWindowMe.open(map,markers[key);
However this code turns all marker into same name with the user instead of different names since im clicking other users marker
Please Help
Here the screenshot I took
You can try this. Hope this helps.
var locations = [
['Location name', LAT, LON],
['...', ..., ...],
//...
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(LAT, LON),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
var lat = locations[i][1];
var lng = locations[i][2];
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
}); // generates all the markers
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
zIndex: 1000;
infowindow.setContent(locations[i][0]); // replace locations[i][0] with which data you want to show
infowindow.open(map, marker);
}
})(marker, i)); // generates corresponding info-window
}

How to show geolocated tweets on a map

I have been playing around with the twitter API getting random tweets or even geo tagged tweets and also with the google maps API. However I want to combine this two and try and show geo tagged tweets on a google map. Here is my code for getting the geo tagged Tweets which work fine.
var geo = (geo.coordinates[0], geo.coordinates[1])
//var geo = (34.052234, -118.243685)
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
for(var index in data.statuses){
var tweet = data.statuses[index];
console.log(tweet.text);
console.log(tweet.geo.coordinates)
}
});
On a different file, I generated a map based on Longitude and Latitude, and I had the understanding that once I had retrieved the coordinates for the tweets, I could represent the tweets on a Google Map in the same way. However, my code is not working. My question is, how would I combine both pieces of code to generate a map which is marked with geo located Tweets?
function initialize() {
var myLatlng = new google.maps.LatLng(geo.coordinates[0], geo.coordinates[1]);
var mapOptions = {
center: myLatlng
zoom: 10,
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Tweet});
var infowindow = new google.maps.InfoWindow({
content: 'Geo tagged Tweet',
maxWidth:200 });
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker); });
}
google.maps.event.addDomListener(window, 'load', initialize);
I would do something like this (untested - I'm just writing down some thoughts).
1) You should strip down init so that it just contains the map set up. Ensure map is declared outside of the function, and include a call to the function that fetches your data using the lat/lng data.
var map;
function initialize() {
var lat = geo.coordinates[0];
var lng = geo.coordinates[1]
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = { center: myLatlng, zoom: 10 }
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
getData(lat, lng, processData);
}
2) You wrap your data fetching code in a new function declaration, which accepts lat/lng data, and a callback.
function getData(lat, lng, callback) {
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
callback(data.statuses);
}
)
};
3) Process the tweet information. For each tweet create a marker (add the marker to an array of markers) and update the map
function processData(data) {
var markers = [];
for (var i = 0, l = data.length; i < l; i++) {
var marker = new google.maps.Marker({
id: i,
position: myLatlng(data[i].geo.coordinates[0], data[i].geo.coordinates[1),
map: map,
title: "Tweet"
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow({
content: data[i].text,
maxWidth: 200
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}

Google Maps adding multiple markers using javascript

So this set of code is pulling in locations (Latitude, Longitude, and Address) from a C# backend.
the backend code pulls data from a SQL database and inputs it into the ASP.Net DataField columns.
It was an enhancement to a prebuilt application to include Google Maps.
The locations pull just fine and stepping through it shows the latitude and longitude correctly.
The issue I'm having is that only one marker shows up which looks to be the last one.
Its as if each location isn't actually adding a new marker, but overwriting the current one which leaves the last location as the marker on the map.
What do I need to change to get each location to show up as a new marker?
<script type="text/javascript">
function locate() {
var inputList = GridView1.getElementsByTagName("td");
var rows = GridView1.getElementsByTagName("tr");
// var markers = inputList[0].innerHTML;
for (i = 1; i < rows.length; i++) {
var lat = rows[i].cells[2].innerHTML;
var lng = rows[i].cells[3].innerHTML;
var addr = rows[i].cells[1].innerHTML;
var mapOptions = {
center: new google.maps.LatLng(rows[1].cells[2].innerHTML, rows[1].cells[3].innerHTML),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var markers = [];
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var data = rows[i]
var myLatlng = new google.maps.LatLng(data.cells[2].innerHTML, data.cells[3].innerHTML);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
markers.push(marker);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.cells[1].innerHTML);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</form>
</body>
</html>
You're creating the map and the marker within the same loop. i.e. you're creating a map with a single marker on it, rows times. You want to create the map outside of your loop. Something like this:
function locate() {
var rows = GridView1.getElementsByTagName("tr");
var mapOptions = {
center: new google.maps.LatLng(rows[1].cells[2].innerHTML, rows[1].cells[3].innerHTML),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (i = 1; i < rows.length; i++) {
var data = rows[i];
var myLatlng = new google.maps.LatLng(data.cells[2].innerHTML, data.cells[3].innerHTML);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.cells[1].innerHTML);
infoWindow.open(map, marker);
});
})(marker, data);
}
}

google map doesnt show any marker

i was trying to use google map api v3 and pop up some markers on the map. un fortunately it doesnt show up on my map. i use array push to store marker with latitude and longitude parameter.
here is my code
<script type="text/javascript">
var trackerMarkerArray = [];
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myLatlng2 = new google.maps.LatLng(-25.363800,131.044900);
var mapOptions = {
center: myLatlng,
zoom: 8
};
try {
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng
});
var marker2 = new google.maps.Marker({
position: myLatlng2
});
trackerMarkerArray.push(marker);
trackerMarkerArray.push(marker2);
for (var i = 0; i<trackerMarkerArray.lenght; i++){
trackerMarkerArray[i].setMap(map);
console.log("value" + trackerMarkerArray[i]);
}
} catch (err){
alert(err);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
for (var i = 0; i<trackerMarkerArray.lenght; i++)
lenght must be "length"
also, when the map is not showing, try to see browser's debug console for any error.

Google Maps api v3 - "Infowindow not defined" Error

The map comes up and the point appears. I have the title appearing as well. But as soon as I click on the marker to get info, nothing appears. Firebug info is below.
The information is being brought in via a database and there are multiple items; multiple markers are shown on the map as they should.
Any help would be apprecaited. Thanks..
Firebug Point Info:
MarkLat[i] = xx.xxxxxxxxxxxxxx;
MarkLong[i] = -xx.xxxxxxxxxxxxxx;
MarkerTitle[i] = 'Title 1';
Display[i] = '<table><tr><td>Title 1</td></tr><tr><td>Title 1 Address<br />Title 1 City, State Zip</td></tr><tr><td>Title 1 Phone</td></tr><tr><td>Title 1 Email</td></tr><tr><td>Title 1 URL</td></tr></table>';
Firebug Error:
infowindow is not defined
infowindow.open(map,marker);
Code:
<script type="text/javascript">
var i = -1;
var MarkLat=new Array();
var MarkLong=new Array();
var MarkerTitle=new Array();
var Display=new Array();
var MapCenter = new google.maps.LatLng(xx.xxxxxxxxxxxxxx,-xx.xxxxxxxxxxxxxx)
</script>
<script type="text/javascript">
var i = i + 1;
MarkLat[i] = [[Lat]];
MarkLong[i] = [[Long]];
MarkerTitle[i] = '[[Title]]';
Display[i] = '<table><tr><td>[[Title]]</td></tr><tr><td>[[Address]]<br />[[City]], [[State]] [[Zip]]</td></tr><tr><td>[[Phone]]</td></tr><tr><td>[[Email]]</td></tr><tr><td>[[WebURL]]</td></tr></table>';
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 12,
center: MapCenter,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
for (var i = 0, length = 50; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addDomListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Changing to a capital W was not enough for me. Only one location was being opened. I tested your code with two points:
MarkLat = [];
MarkLong = [];
Display = [];
MarkerTitle= [];
MarkLat[0] = 0;
MarkLong[0] = 0;
Display[0] = { content: "hi" };
MarkerTitle[0] = "hello";
MarkLat[1] = 10;
MarkLong[1] = 10;
Display[1] = { content: "hi 2" };
MarkerTitle[1] = "hello 2";
I'm guessing you only want one InfoWindow on the screen at any given time. Then, a single InfoWindow should be declared, with the contents kept inside the marker, and have the contents change as the marker is clicked.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i],
infoWindowContent: Display[i]
});
// Notice I used the 'this' keyword inside the listener
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(this.infoWindowContent.content);
infoWindow.open(map,this);
});
}
The alternative, having many InfoWindows pop up, needs a change to click listener, so that a reference to each individual InfoWindow is preserved. This effect is accomplished with an anonymous function wrapped around the infoWindow.open function (a new function scope is created).
for (var i = 0, length = Display.length; i < length; i++) {
var latLng = new google.maps.LatLng(MarkLat[i],MarkLong[i]);
var infoWindow = new google.maps.InfoWindow(Display[i]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: MarkerTitle[i]
});
google.maps.event.addListener(marker, 'click', (function(infoWindow) {
return function() {
infoWindow.open(map,this);
}
})(infoWindow));
}
infowindow != infoWindow
You just have declared it with a capital, trying to use it without

Categories

Resources