How to save latitude, longitude in my db. Using leaflet map

Viewed 472

I am building an app that uses leaflet map and mongoDB as my db. I want the user to be able to click on a place on the map and edit the details on the marker and then i want to save these places on my db. How do i do that? I am relatively new and i have to do this for my diploma thesis and i have no previous experience with databases and javascript. I have already setup my db using mongoose.

I searched on stackorverflow for a similar question but i couldn't find anything new, if i just missed it, please redirect me there.

Thanks!

1 Answers

Saving data into the database.

// 1. make a mongoose model
const schema = new mongoose.Schema({
  name: {
    type: String,
    default: "Placeholder Location Name"
  },
  coordinates: {
    type: [Number],
    default: [0, 0]
  }
});
const Location = mongoose.model('Location', schema);

// 2. example of making a Location
const exampleLocation = new Location({
  name: "My First Location",
  coordinates: [41.40338, 2.17403] // This is where your example coordinates go.
})

exampleLocation.save((err) => {
  if (err) console.log("An error occured while trying to save: " + err)
  else console.log("Success") // the object is saved
})

Capturing a click on the map

let map = document.getElementById('your-leaflet-map-id')

map.addEventListener('click', (event) => {
  console.log('The clicked coordinates were: ' + event.latlng.lat + ',' + event.latlng.lng)
  // feel free to use these coordinates as you wish
  yourMethodToSaveLocation(event.latlng.lat, event.latlng.lng)
})
Related