Google Maps - Saving a dynamic map - javascript

I'm attempting to create a dynamic map using the latest Google Map API. Everything is going smooth so far. I do have a question of course:
How would I/you go about saving my current map?
Let's say you build a map with dynamic markers: Since everything is done via JavaScript, I need to get/set those values from a file/database.
I was thinking about outputting the entire google.map.Markers as a JSON and send it to a database as a string, but then if I have around 100 places, I'm not sure how well it would go and I'm worried about efficiency.
Is this the only way to do it and am I thinking properly? Basically your website users are allowed to place a marker on the map, which then are subject to confirmation of course. Once it's confirmed, that marker must be in the latest "version" of the map, so I must get that info from/into a database/file.
Thanks in advance!

I'm creating similar application and I implemented it this way:
I have a Marker table which has columns for each attribute that I'm using in markers (e.g. latitude, longitude, name, description, type, etc.) When someone adds a marker I'm just saving the attributes of the marker to the database. Next time I want to show the marker I'm just getting the attributes from database, encode them to JSON and attach to the page. Inside page I have the JS that grabs those attributes and creates the markers inside the map. Pseudocode:
//this is generated dynamically from DB.
var markers = [
{lat:115416,lng:26411},
{lat:115416,lng:26411}
];
//this is static, just grabs the dynamic bit and puts it on the map:
for (var i = 0; i < markers.length; i++){
//creates a marker object
var marker = new Marker({lat:markers[i].lat, lng:markers[i].lng })
//displays it on the map
map.addMarker(marker);
}
the benefit of this is that your data in the database is independent from map implementation, e.g. if in the future you decide to move to apple maps and it has different implementation you can just write different JS to handle the data. Also you can query over it, e.g. you can query for places that are close by looking at lat and lang, etc..

Related

Creating map by CARTO from table with zero the_geom parameter

I have added new dataset to carto Builder using .csv file. But there is null the_geom column. So when i create map using reactjs and carto.js via:
this.cartoClient = new carto.Client({ apiKey: 'key', username: 'user' });
<Map center={center} zoom={zoom} ref={node => { this.nativeMap = node && node.leafletElement }}>
<Basemap attribution="" url={CARTO_BASEMAP} />
<Layer
source={airbnb.source}
style={this.state.layerStyle}
client={this.cartoClient}
hidden={this.state.hidelayers}
/>
</Map>
and using airbnb.source
SELECT
cartodb_id, field_1,field_8, field_7, field_6, field_2, field_4, field_3, field_5,
ST_SetSRID( ST_MakePoint(
field_4,
field_3
),
4326
) AS the_geom,
ST_Transform(ST_Buffer(the_geom,0.001), 3857) as the_geom_webmercator
FROM (SELECT * FROM allreports) AS _camshaft_georeference_long_lat_analysis
Carto.js does not mark points on my map, so i get it clear. How should i workaround the_geom,the_geom_webmercator to get the map with points or the problem is somewhere else?
Does same SQL work in Builder? From where did you get it? Without seeing actual data one can only speculate what can be done, also your field names are not very helpful here. Or is it auto-generated SQL from Builder? I'm not sure if it is good idea to hack around that one, even if it works now, then these internal structures can change anytime. In general there are following scenarios how you get data to map:
Importer tries some heuristics from table structure to add it to map. For example if you have column names latitude and longitude, then the table will automatically geocoded, i.e. geom fields are filled and the table just works. Or if there is column city with English city names, then there is good chance also that it will be on map. So the easiest way is to use these field names, if you already have it in your data.
You can persistently geocode table using Carto SQL API, with something like UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column}, {province_column}, {country_column}) in the case of named places, or if you have wgs lat/lon fields then UPDATE {tablename} SET the_geom = st_setsrid(st_point({lon_column}, {lat_column}),4326). This way the the_geom will be filled. To make it sure I would also do UPDATE {tablename} SET the_geom_webercator = st_transform(the_geom, 3857). Of course you can use here st_buffer etc.
you can do also live geocoding query as you seem to try now, just be sure that there is unique cartodb_id, proper the_geom (in wgs84) and the_geom_webmercator (in epsg3857 projection, just as you have). This makes more sense if your data is somehow dynamically updated, otherwise I would do one-time UPDATE to the table.
use Builder geocoding analysis. This creates another 'virtual' live dataset with geocoded data, and this can be used in map view or further analyses. I'm afraid this cannot be done/shown in carto.js maps, this is within Builder only.
p.s. you can find more carto-related posts in https://gis.stackexchange.com/questions/tagged/carto

How can Google Maps markers be used in objects?

I have an array "markerGroups" defined like this:
var markerGroups = {"foo": [], "bar": [], "foobar": []};
This array is used for storing all the markers in a Google Map. As you can see, I have three categories where I store the markers. One marker will only exist in one category, and will never exist in any other category.
Each marker is also identyfied by a unique ID, for instance the ID can be 1422.
Now I want to add the markers to this group in such a way that i can reach it by doing for instance
console.log(markerGroups.foo[1422]);
Even if that's the only marker in that category. I must also be able to remove it completly from the category.
I have tried to make this possible by defining markerGroups like this:
var markerGroups = {"foo": {}, "bar": {}, "foobar": {}};
This line is in a function where the marker is defined as marker, and category is passed into the function, telling the function where to store the marker.
markerGroups[category][marker.ID] = marker;
This works excellent, except the fact that markers now won't show up in my map.
Any ideas why or how this could be done in a better way?
Markers are simple JS objects that can be manipulated in the same way that any JS object can.
The only way you can control if a Marker is shown on the map is via it's setMap() function. So check out your code and see if you call setMap(your_map) for the markers you want to be shown on the map. Also bear in mind that there are some properties that must be set (position for example) in order the Marker to be shown.
So, don't worry of simple JS object manipulation, it doesn't interact with the Marker visibility, as long as it's initialized properly.
Of course, this is a theoretical point of view, if you've done all this and it still doesn't work, you must provide some additional details and code.

How to dynamically change a google maps marker after its added

Using the google maps API (v3) I can successfully add an array of markers to the map using custom icons.
Each marker represents a destination and I want to change the icon image when the respective destination name is mouse'd over elsewhere on the page.
I can add the event listener to pick up the mouse over, and I know I can use marker.setIcon("imgurl") to change the icon, however what I can't figure out is how to reference the specific marker to be changed?
I've read that I can add an "id" when defining the marker, however I can't figure out how to use this is conjunction with marker.seticon to update that specific marker.
Thanks for your help.
If you have ID numbers for each destination, keep an array of the markers indexed by your destination.
For example,
var myMarkers = []
for(var i = 0; i < destinations.length; i++) {
myMarkers[destination[i].id] = new google.maps.Marker(markerOpts)
}
and in your destination links elsewhere:
onclick = function() {
myMarkers[destinationID].setIcon(otherIcon)
}
I typically create an array called markersArray. Then I name each marker marker_1, marker_2, etc. using a for loop. After each one is created, I push it to the markersArray. Now you can reference each marker using markersArray[i].

How do I store more information in a marker?

I'm using Google Maps v3 and I build in the server side a json collection of location data. So when I receive that, I iterate through that collection and create a marker object for each and every one of them.
For each of these markers, I bind them with the click event, so when the user clicks on a marker in the map, it displays an infoWindow with data related to the associated location.
I have an array to store all the location got from the server that holds the retrieved json objects and their corresponding marker.
The problem is that, even when I have an array that I can reference or iterate through, I need to not only get the marker object when the user clicks on them, but also the location object, that stores more information.
I tried to mantain this array of objects and reference it from the calling object without success, because the function is called by the marker and not the location object. So I thought if it's possible to store more information in the google maps marker object like using a general purpose field.
Please let me know if more information is needed.
Thanks!
Yes you can, thanks to JavaScript. In this language, objects and hashtables are the same thing1.
This is how you are creating your marker:
var point = new google.maps.LatLng(40.70, -74.00);
var myMarker = new google.maps.Marker({ position: point, map: map });
And this is how you can add an additional property to your myMarker object:
myMarker.myNewField = 100;
Voila! No need to hold separate arrays of related data. No need of a general purpose field. Simply invent a new property name, and you're good to go.
1 A Survey of the JavaScript Programming Language by Douglas Crockford.

Google Maps & jQuery InfoWindow Replacement

So I'm rewriting my first google maps app and I'm looking at how I create info windows on click of a marker and it seems very inefficent to be adding a listener for each. Previously I've used GInfoWindow and EBubble (http://econym.org.uk/gmap/ebubble.htm).
I was thinking that I could use jQuery to show a div with dynamic data if I had a hook for each marker to show the window and relevant marker info (pulled from JSON). I can see each marker has a unique id (e.g. mtgt_unnamed_2822) but I'm not sure how to predicte this.
Has anyone tried this before or know how to go about it?
Thanks
Denis
I don't know jQuery, but Javascript allows you to add your own custom Properties to any Object. So you can write stuff like this:
var marker = new GMarker(...);
marker.ID = "mtgt_unnamed_2822";
or
function createMarker(point,newid) {
var marker = new GMarker(point);
marker.ID = newid;
...
}
Be careful not to use "marker.id" because the API could use "id" as the obfuscated internal name for an existing property in some future release. In fact avoid Property names that start with a lower case letter.
Once you've attached the .ID Property to a marker, you can read the info from the marker.ID of any marker reference whenever you need it to make the jQuery call.

Categories