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);
});
}
}
Related
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>
How to display google map after every x seconds without google map refresh?
1.Markers latLong are coming from database.
2.Allocate that markers on google map.
3.Markers's latLong changes after 30 second.
Problem is google map get refreshed. All I want google map should display without refresh with updated LatLong.
Here is my code.
<script>
function initMap() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
var image = '<?php echo $getImagePath; ?>'
for (var o in markers) {
lat = markers[ o ].lat;
lng = markers[ o ].lng;
address = markers[ o ].address;
var my = new google.maps.LatLng(lat, lng);
//console.log(my);
var marker = new google.maps.Marker({
position: my,
map: map,
icon: image,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("'" + address + "'");
infowindow.open(map, marker);
});
}
}
</script>
I tried google.maps.event.addDomListener(window, "load", initMap); and window.onload = initMap; but didn't work.
Can any one help me out?
I hope this small rewrite of your code will help you on your way. As it stands, there's a lot of information not present in the question, so I can only guess
// note these are globals because they are set in initMap and used outside of it
var image = '<?php echo $getImagePath; ?>';
var map;
var infowindow;
var markers = [/* some initially loaded markers loaded as if by majick unicorn farts */];
function initMap() {
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
doMarkers(true);
}
function doMarkers(firstLoad) {
markers.forEach(marker => {
var lat = marker.lat;
var lng = marker.lng;
marker.my = new google.maps.LatLng(lat, lng);
if (firstLoad) { // marker has no marker the first time because it's not on a map yet
marker.marker = new google.maps.Marker({
position: marker.my,
map: map,
icon: image,
});
google.maps.event.addListener(marker.marker, 'click', function () {
infowindow.setContent("'" + marker.address + "'");
infowindow.open(map, marker.marker);
});
} else { // move existing marker
marker.marker.setPosition(marker.my);
}
}
}
function magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker) {
// find corresponding marker in markers array
// update lat, lng and address
}
function doSomeAjaxToGetNewMarkerPositionsAndCallCallback(cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'someURI');
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
data.forEach(function(marker) {
magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker);
});
cb()
}
xhr.send();
}
setInterval(function () {
doSomeAjaxToGetNewMarkerPositionsAndCallCallback(function() {
doMarkers(false);
});
}, 30000);
Of course, I can't see how markers are loaded (into markers in your code), nor can I tell you what doSomeAjaxToGetNewMarkerPositionsAndCallCallback or magicallyFindAndUpdateMarkerDataUsingUnicornFarts should be, because you haven't shown any code regarding markers at all
I receive json data from a server and need to add them to a google map. It works fine, however, I only see one marker and I assume every time I add a marker it changes it to new coordinates and doesnt add an extra marker. How can I define markers as an array?
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: this["gsx$instruments"][prop]
});
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Add a new function addMarker and use that function to include markers also keep the map variable outside the ajax call as well. updated code below
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: {lat: LAT, lng: LONG}
});
function addMarker(position, map, title){
var marker = new google.maps.Marker({
position: position,
map: map,
title: title
});
}
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
addMarker(myLatLng,map,this["gsx$instruments"][prop]);
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Essentially, you first need to add the markers to an array of markers
Suppose you have JSON providing the markers and supposing each marker has a name and coordinates attributes
function formatMarkers (){
// Loop through all of the JSON entries provided in the response
for (var i = 0; i < markersArray.length; i++) {
var markers = markersArray[i];
// Create popup windows for each record
var contentString = '<p><b>Name</b>: ' + markers.name + '</p>';
// Converts each of the JSON records into Google Maps Location format
formattedMarkers.push({
latlon: new google.maps.LatLng( markers.coordinates[1], markers.coordinates[0] ),
message: new google.maps.InfoWindow({
content: contentString,
maxWidth: 320
}),
username: markers.name
});
}
return formattedMarkers;
}
Then you need to render each of them
formattedMarkers.forEach(function (n) {
var marker = new google.maps.Marker({
position: n.latlon,
map: map,
icon: icon
});
// For each marker created, add a listener that checks for clicks
google.maps.event.addListener(marker, 'click', function () {
// When clicked, open the selected marker's message
n.message.open(map, marker);
});
marker.setMap(map);
}
I hope I've been helpful.
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);
}
}
I am using google maps and I am trying out places API, but something makes me wonder...
If you load maps.google.com and go to Kuala Lumpur, then type "food" in the search-box, you will see hundreds of restaurants on the map. I would like to get these into my own maps.
Using the Places API, I have pretty much copied their example code:
function initialize() {
var plat = 3.15;
var plong = 101.7;
var ppos = new google.maps.LatLng(plat, plong);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: false,
zoom: 10,
center: ppos
};
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
var request = {
location: ppos,
radius: '10000'
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: place.icon
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("<b>" + place.name + "</b><br/>" + place.vicinity);
infowindow.open(map, this);
});
}
When I execute this code, I do get results, but only very few and only major locations like a few malls and museums. So, How do I get all that beautiful data, that I see on Google's own map?
So it turned out there were a number of problems:
Categorization is broken in Inodesia, so using keyword instead solved the problem, as in:
var request= {
location: ppos,
radius: 10000,
keyword: 'restaurant' }
keyword takes a string rather than an array, and radius takes a number rather than a string. You can see a summary of the types for the request here: http://code.google.com/apis/maps/documentation/javascript/reference.html#PlaceSearchRequest